C++ Lexicographical comparison


Example

Two std::strings can be compared lexicographically using the operators ==, !=, <, <=, >, and >=:

std::string str1 = "Foo";
std::string str2 = "Bar";

assert(!(str1 < str2));
assert(str > str2);
assert(!(str1 <= str2));
assert(str1 >= str2);
assert(!(str1 == str2));
assert(str1 != str2);

All these functions use the underlying std::string::compare() method to perform the comparison, and return for convenience boolean values. The operation of these functions may be interpreted as follows, regardless of the actual implementation:

  • operator==:

    If str1.length() == str2.length() and each character pair matches, then returns true, otherwise returns false.

  • operator!=:

    If str1.length() != str2.length() or one character pair doesn't match, returns true, otherwise it returns false.

  • operator< or operator>:

    Finds the first different character pair, compares them then returns the boolean result.

  • operator<= or operator>=:

    Finds the first different character pair, compares them then returns the boolean result.

Note: The term character pair means the corresponding characters in both strings of the same positions. For better understanding, if two example strings are str1 and str2, and their lengths are n and m respectively, then character pairs of both strings means each str1[i] and str2[i] pairs where i = 0, 1, 2, ..., max(n,m). If for any i where the corresponding character does not exist, that is, when i is greater than or equal to n or m, it would be considered as the lowest value.


Here is an example of using <:

std::string str1 = "Barr";
std::string str2 = "Bar";

assert(str2 < str1);

The steps are as follows:

  1. Compare the first characters, 'B' == 'B' - move on.
  2. Compare the second characters, 'a' == 'a' - move on.
  3. Compare the third characters, 'r' == 'r' - move on.
  4. The str2 range is now exhausted, while the str1 range still has characters. Thus, str2 < str1.