Search code examples
c++operator-overloadingstring-comparisonstdstring

Using the less than comparison operator for strings


I'm following a tutorial for C++ and looking at strings and overloading with operators such as +=, ==, != etc. Currently I have a simple if-statement:

if(s1 < s2)
    cout << s2 <<endl;
else
  if(s2 < s1)
    cout << s1 << endl;
  else
    cout << "Equal\n";

But how does this work, and how does the program decide which string is greater than another? looking around I've found a basic template declaration:

template<class charT, class traits, class Allocator>
bool operator< ( const basic_string<charT,traits,Allocator>& lhs,
                 const basic_string<charT,traits,Allocator>& rhs );

Does this define how < works? If so, what does <charT,traits,Allocator> mean / do?

Also do the following operators have any meaning for strings? -= and *=


Solution

  • The less-than operator on strings does a lexicographical comparison on the strings. This compares strings in the same way that they would be listed in dictionary order, generalized to work for strings with non-letter characters.

    For example:

    "a" < "b"
    "a" < "ab"
    "A" < "a"             (Since A has ASCII value 65; a has a higher ASCII value)
    "cat" < "caterpillar"
    

    For more information, look at the std::lexicographical_compare algorithm, which the less-than operator usually invokes.

    As for -= and *=, neither of these operators are defined on strings. The only "arithmetic" operators defined are + and +=, which perform string concatenation.

    Hope this helps!