I am using C++ stable_sort to sort a vector of my class objects in ascending order using a comparator function, but the sort is not stable. A work around that worked was to reverse iterate and reversing the logic in the comparator. But cant understand why it shouldnt work normally. Code:
using namespace std;
class Pair{
string str;
int num;
public:
Pair(string s, int n):str(s), num(n)
{}
Pair(const Pair &a)
{
str = a.str;
num = a.num;
}
int Num()
{
return num;
}
string Str() const{
return str;
}
void set(string s, int n)
{
str = s;
num=n;
}
void print() const{
cout<<"\n"<<num<<" "<<str;
}
};
bool comparator( Pair a, Pair b)
{
return a.Num()<=b.Num();
}
int main() {
int n;
cin >> n;
vector<Pair> arr;
for(int a0 = 0; a0 < n; a0++){
int x;
string s;
cin >> x >> s;
if((a0+1)<=n/2)
s="-";
Pair p(s, x);
arr.push_back(p);
}
cout<<"\n Before sort";
for(auto i:arr)
i.print();
stable_sort(arr.begin(), arr.end(), comparator);
cout<<"\n\n After sort";
for(auto i:arr)
i.print();
return 0;
}
Result: Before sort 0 - 6 - 0 - 6 - 4 - 0 - 6 - 0 - 6 - 0 - 4 that 3 be 0 to 1 be 5 question 1 or 2 not 4 is 2 to 4 the
After sort 0 to 0 - 0 - 0 - 0 - 0 - 1 or 1 be 2 to 2 not 3 be 4 the 4 is 4 that 4 - 5 question 6 - 6 - 6 - 6 -
comp - comparison function object (i.e. an object that satisfies the requirements of Compare) which returns true if the first argument is less than (i.e. is ordered before) the second.
from stable_sort. The comparator must implement a strict weak ordering. See also here for a table of the exact requirements.
Your comparator is wrong, it also returns true for equal elements.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With