Quantcast
Channel: Why is const required for 'operator>' but not for 'operator
Viewing all articles
Browse latest Browse all 3

Answer by StoryTeller - Unslander Monica for Why is const required for 'operator>' but not for 'operator

$
0
0

You get different behaviors because you are in fact calling two different (overloaded) sort functions.

In the first case you call the two parameter std::sort, which uses operator< directly. Since the iterators to your vector elements produce non-const references, it can apply operator< just fine.

In the second case, you are using the three parameter version of std::sort. The one that accepts a functor. You pass std::greater. And that functor has an operator() declared as follows:

constexpr bool operator()( const T& lhs, const T& rhs ) const;

Note the const references. It binds the elements it needs to compare to const references. So your own operator> must be const correct as well.

If you were to call std::sort with std::less, your operator< will produce the same error, because it's not const-correct.


Viewing all articles
Browse latest Browse all 3

Trending Articles