[英]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:我正在关注 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 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?如果是这样,
<charT,traits,Allocator>
是什么意思/做什么?
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.有关更多信息,请查看
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.定义的唯一“算术”运算符是
+
和+=
,它们执行字符串连接。
Hope this helps!希望这可以帮助!
The comparison operators implement lexicographic ordering of strings.比较运算符实现字符串的字典顺序。
-=
and *=
are not defined for strings. -=
和*=
不是为字符串定义的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.