Using the less than comparison operator for strings

南笙酒味 提交于 2019-11-26 16:55:02

问题


I'm following a tutorial for C++ and looking at strings and overloading with operators such as +=, ==, != etc, currently 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 decleration:

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 mean / do?

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

any advice is greatly appreciated!


回答1:


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!




回答2:


The comparison operators implement lexicographic ordering of strings.

-= and *= are not defined for strings.



来源:https://stackoverflow.com/questions/13829434/using-the-less-than-comparison-operator-for-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!