简体   繁体   中英

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

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!

The comparison operators implement lexicographic ordering of strings.

-= and *= are not defined for strings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM