Namespaces
Variants
Actions

Talk:cpp/algorithm/lexicographical compare

From cppreference.com

Why do the implementations use a postfix increment instead of a prefix increment, and why the cast to void? Prefix is more economical, and the void is quite useless, the compiler can see we discard the return value. 82.225.76.247 11:14, 6 December 2016 (PST) Akim.Demaille

the cast to void protects against element types that overload operator comma. Feel free to make them pre-increments if you like. In fact, libc++ uses++__first1, (void)++__first2) --Cubbi (talk) 13:56, 6 December 2016 (PST)

Why is std::random_shuffle is used in example even though it's deprecated/removed? --Predelnik (talk) 06:45, 21 August 2017 (PDT)

because the example was old. Updated, thanks. --Cubbi (talk) 10:06, 22 August 2017 (PDT)

[edit] Error regarding explantion

The current explanation what Lexicographical comparison is, is wrong: I currently read:

  • The first mismatching element defines which range is lexicographically less or greater than the other.

That's wrong. Here's a code example showing it to be wrong:
https://wandbox.org/permlink/j6fRjcuMmKU5c7zx

Correctly it should read:

  • The first element for which the comparison operator returns true, when given arguments in normal order (e.g. (a1, a2) - lexicographically less) or in swapped order (e.g. (a2, a1) - lexicographically greater), defines which range is respectively lexicographically less or greater than the other.

Please also add a warning note to the wiki, along the following lines:

Warning Note:
It should be noted that a comparison function which returns true when comparing a value to itself (e.g. (a1, a1)), such as <= or >= ; will lead to the following surprising ordering: e.g.
{1, 100} is lexicographically less than {1, 999}
{1, 999} is lexicographically less than {1, 100} (also!! this is no error!)
To get the more natural ordering, that does not shortcut the comparision, use a comparision function for which a comparison of a value with itself returns false; e.g. < or >

Your comparison function doesn't establish a strict weak ordering (required by the Compare requirement), and so shouldn't be used with std::lexicographical_compare --Ybab321 (talk) 07:24, 23 September 2020 (PDT)
True. I missed that. I suppose if the compare function is constexpr (ref), one could fail via static_assert if the compare function does not satisfy Compare requirement Faisoe (talk) 12:48, 23 September 2020 (PDT)
close