21

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 *=

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
Dmist
  • 345
  • 1
  • 2
  • 4
  • Since `std::string` is actually a `typedef` for `std::basic_string, std::allocator>`, one particular instantiation of that function template is `bool std::operator<(const std::string&, const std::string&);`, which is presumably called by your `s1 < s2` and `s2 < s1` expressions. – aschepler Dec 11 '12 at 22:23

2 Answers2

34

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
  • The `"A" < "a"` is an ASCII assumption and doesn't work for other character sets, like [EBCDIC](http://en.wikipedia.org/wiki/EBCDIC). :-) – Bo Persson Dec 11 '12 at 22:27
  • Also there's probably a general warning due: Lexicographical sorting is generally a bad idea if used in the UI. Not only are the results dependent on the actual encoding (and generally confusing), it's basically completely wrong for unicode. – Voo Dec 11 '12 at 22:36
  • Hey, thanks very much for the answers, knew there had to be a simple explanation! – Dmist Dec 11 '12 at 23:45
  • String comparisons almost certainly does not invoke `lexicographical_compare`, though the algorithm used might be similar. – T.C. May 06 '15 at 17:12
2

The comparison operators implement lexicographic ordering of strings.

-= and *= are not defined for strings.

NPE
  • 486,780
  • 108
  • 951
  • 1,012