Tony I.
Tony I.

Reputation: 632

Why does is_sorted not work correctly with greater_equal?

I have C++ code:

auto test = vector<unsigned int>({3, 2, 1});
assert(is_sorted(test.begin(), test.end(), greater_equal<unsigned int>())); //passes

test = vector<unsigned int>({3, 1, 1});
assert(is_sorted(test.begin(), test.end(), greater_equal<unsigned int>())); //fails

Why does second one fail?

Upvotes: 1

Views: 564

Answers (2)

Felix Dombek
Felix Dombek

Reputation: 14382

greater_equal can be used with is_sorted specifically to forbid multiple identical elements, thus enforcing a strict ordering (same, but ascending, for less_equal).

Note that the predicate is used in negation:

A sequence is sorted with respect to a comparator comp if for any iterator it pointing to the sequence and any non-negative integer n such that it + n is a valid iterator pointing to an element of the sequence, comp(*(it + n), *it) evaluates to false. (cppreference)

Upvotes: 0

eerorika
eerorika

Reputation: 238461

is_sorted has requirements for the comparison function object. In particular, it must satisfy the requirements of Compare concept. The same requirement is for most (all?) comparison objects used by the standard library .

std::greater_equal does not satisfy the requirements of Compare concept. In particular, it does not satisfy the irreflexivity: For all a, comp(a,a)==false nor asymmetry: If comp(a,b)==true then comp(b,a)==false (for all a,b) properties. In other words, std::greater_equal is not a strict weak ordering.

As pointed out by aschepler, std::greater satisfies the Compare concept, so that's probably what you are looking for.

Upvotes: 2

Related Questions