我正在用 C++ 授课,所以我们的主题是关于运算符重载,来 self 正在使用的教科书“C++ 如何为 Deitel 编程”,还有这个例子,他比较了 2 个逻辑上不存在的字符串'没有任何意义。
我的问题在下面的例子中。与使用 alphabool 相比,为什么 s2 比 s1 小?
#include <iostream>
#include <string>
using namespace std;
int main() {
string s1{ "happy" };
string s2{ " birthday" };
string s3; // creates an empty string
// test overloaded equality and relational operators
cout << "s1 is \"" << s1 << "\"; s2 is \"" << s2
<< "\"; s3 is \"" << s3 << '\"'
<< "\n\nThe results of comparing s2 and s1:"
<< "\ns2 == s1 yields " << (s2 == s1)
<< "\ns2 != s1 yields " << (s2 != s1)
<< "\ns2 > s1 yields " << (s2 > s1)
<< "\ns2 < s1 yields " << (s2 < s1)
<< "\ns2 >= s1 yields " << (s2 >= s1)
<< "\ns2 <= s1 yields " << (s2 <= s1)
<<"Size of string s1 is:"<<s1.length()
<<"Size if string s2 is:"<<s2.length();
}
最佳答案
s2
开头的空格符出现在 h
之前在s1
的开头在 ASCII 图表中,所以 s2
首先排序。幸运的是,如果这不是您想要的行为,标准库包含使用不同排序算法的方法。例如,某些版本的 std::lexicographical_compare
采用 Compare
类型的参数它可以是接受两个相同类型的元素并返回 true
的任何函数当且仅当两个元素按所需顺序排列时。 (您也可以使用“类似函数的对象”,即实现 operator()
的类,它采用两个元素并返回 bool
)。同样,类似 std::set
的容器和 std::map
保持元素排序的模板类型参数 Compare
可用于按您喜欢的方式对它们的元素进行排序。
现在,与只做 s1 < s2
相比,这听起来像是很多工作,嗯?好吧,如果你愿意,你可以用它自己的 operator<
创建你自己的字符串类。随心所欲地实现。一种方法是这样的:
class myString: public std::string
{
// ...
};
bool operator<(const myString &ms1, const myString &ms2)
{
return std::lexicographical_compare(ms1.begin(), ms1.end(), ms2.begin(), ms2.end(), customComparison);
}
现在,根据您的操作方式,您确实需要小心一些 - 在这种情况下,您需要注意不要交出 myString
反对期待 std::string
的东西,因为它会尝试将它们排序为 std::string
对象 - 但如果您决定它是您想要做的事情,则有多种技术可以缓解这种情况。
关于c++ - 字符串比较运算符的含义是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43753234/