Stable std::partial_sort in C++

Viewed 91

As far as i know there is no something like "std::stable_partial_sort" in STL.

Is there known alternative or best practice to achieve this?

Below is code that partially sort std::vector when collection

is kind of pairs, however the output is not stable. (i would like that 1-AA would appear first) also i care only for the sorted range, if there are other elements that start with 1 keep only the myEmployVec.begin() + N that appear first, outside of the range it is OK if sort is not stable. Expect: 1-AA, 1-AA, 1-AB and if there are more 1-* their order not important.

enter image description here

Is there a recommended way how can achieve stable sort partial sort without using std::stable_sort on the whole vector?

Below is code with std::partial_sort which is not fulfill my request.

// std::partial_sort is not stable.

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>

struct Collection
{
    size_t m_id;
    std::string m_token;
};

bool operator<(const Collection& lhs, const Collection& rhs)
{
    if(lhs.m_id < rhs.m_id)
        return true;
    return false;
}

std::ostream& operator<<(std::ostream& os, const Collection& rhs)
{
    os << rhs.m_id << "-" <<  rhs.m_token;
    return os;
}


int main()
{
    std::vector<Collection> myEmployVec {{4, "ABC"},{1, "AA"}, {5, "A"}, {4, "OTHER"}, {5, "OOO"}, {1, "AA"}, {1, "AB"}};
    std::for_each(myEmployVec.begin(), myEmployVec.end(), [](const auto& elem) { std::cout << elem << " ";});
    std::cout << std::endl;
    
    std::partial_sort(myEmployVec.begin(), myEmployVec.begin() + 3, myEmployVec.end(), std::less<Collection>());
    
    std::for_each(myEmployVec.begin(), myEmployVec.end(), [](const auto& elem) { std::cout << elem << " ";});
    std::cout << std::endl;

    return 0;
}

PS: i can use C++ 98 till 17 only.

Thanks a lot!

0 Answers
Related