Lexicographical comparison

suggest change

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:

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

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

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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents