3
#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

5
  • 3
    Could you please add full text of the error? Commented Jul 11, 2020 at 17:35
  • Aside, a default Test object will have an unitialized value field. Commented Jul 11, 2020 at 17:37
  • Do you want to order in descending order? Commented Jul 11, 2020 at 17:49
  • 1
    The problem is that the comparator function yoyr passing to sort, return true for equal elemtents Commented Jul 11, 2020 at 17:52
  • You cannot negate operator< and use it for sorting, as !(a < b) is equal to a >= b. Commented Jul 11, 2020 at 18:17

1 Answer 1

6

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; });
Sign up to request clarification or add additional context in comments.

3 Comments

@BerianidzeLuka Debug assertions are not executed in Release mode.
You said that sort comparator must return false for equal items,but how this problem is fixed in release? operator stays < like it is
If you do not return false for equal items then your program has undefined behaviour. Working is one possible outcome of undefined behaviour, but obviously you cannot rely on that. The program is still incorrect even if the bug does not show itself.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.