C++ 对字符串使用小于比较运算符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13829434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 17:44:41  来源:igfitidea点击:

Using the less than comparison operator for strings

c++operator-overloadingstdstring

提问by Dmist

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

我正在关注 C++ 的教程,并查看字符串和使用 +=、==、!= 等运算符重载,目前有一个简单的 if 语句

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!

任何意见是极大的赞赏!

回答by templatetypedef

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_comparealgorithm, which the less-than operator usually invokes.

有关更多信息,请查看std::lexicographical_compare小于运算符通常调用的算法。

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

至于-=and *=,这两个运算符都没有在字符串上定义。定义的唯一“算术”运算符是+and +=,它们执行字符串连接。

Hope this helps!

希望这可以帮助!

回答by NPE

The comparison operators implement lexicographic orderingof strings.

比较运算符实现字符串的字典顺序

-=and *=are not defined for strings.

-=并且*=不是为字符串定义的。