当使用覆盖 bool operator<(const std::string & rhs)
时,字符串是否按字典顺序进行比较?运算符(operator)?例如:
std::string str1 = "aabbcc"
std::string str2 = "bbaacc"
(str1 < str2) == std::lexicographical_compare(str1.begin(),str1.end(),str2.begin(),str2.end()) // is this statement true?
最佳答案
是的。
String 的比较运算符是根据其 traits::compare
定义的(即 char_traits<char>::compare
)(C++03 21.3.6.8) 指定返回一个基于其参数 (21.1.1) 的字典顺序的值。
X::compare(p,q,n) ... yields: 0 if for each i in [0,n), X::eq(p[i],q[i]) is true; else, a negative value if, for some j in [0,n), X::lt(p[j],q[j]) is true and for each i in [0,j) X::eq(p[i],q[i]) is true; else a positive value.
实际上,这意味着比较字符串不能区分区域设置(在某些区域设置中可能是非字典顺序的,例如我的)。
关于C++:按字典顺序比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10066328/