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(str1 > str2);
assert(!(str1 <= str2));
assert(str1 >= str2);
assert(!(str1 == str2));
assert(str1 != str2);

These operators return bool. Their results match std::string::compare(), which returns a negative value, zero, or a positive value. The comparisons work as follows:

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 the character pairs are str1[i] and str2[i] for i = 0, 1, 2, …, max(n, m) − 1. 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