Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort algorithm c++

Tags:

c++

sorting

#include <iostream>
#include <array>
#include <algorithm>
using namespace std;
class Test
{
private:
    int value;
public:
    Test()
    {
 
    }
    Test(int _value)
    {
        value = _value;
    }
    bool operator<(Test&);
 
};
bool Test::operator<(Test& rValue) {
    return this->value < rValue.value;
}
int main()
{
    Test* arr = new Test[950];
    arr[0] = Test(5);
    arr[1] = Test(10);
    arr[2] = Test(7);
    arr[3] = Test(3);
    arr[4] = Test(10);
    sort(arr, arr + 5, [](Test& a, Test& b) { return a < b ? false : true; });
}

Sort algorithm works perfectly until there are objects with same grade value.

P.S I know other way to use sort and reverse.

I'm using visual studio 2019

ERROR: Debug Assertion Failed! Expression: invalid comparator

like image 662
Tavkhelidzeluka Avatar asked Feb 16 '26 23:02

Tavkhelidzeluka


1 Answers

A sort comparator must return false for items that are equal, yours returns true.

Try this instead.

sort(arr, arr + 5, [](Test& a, Test& b) { return b < a; });
like image 75
john Avatar answered Feb 19 '26 11:02

john



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!