我刚读了一些使用建议

std::string s = get_string();
std::string t = another_string();

if( !s.compare(t) ) 
{

而不是

if( s == t )
{

我几乎总是使用最后一个,因为我习惯了它,它感觉更自然,更可读。我甚至不知道还有一个单独的比较函数。 更准确地说,我认为==将调用compare()。

有什么不同?在哪些情况下,一种方式比另一种方式更受青睐?

我只考虑需要知道一个字符串是否与另一个字符串的值相同的情况。


当前回答

Compare()等价于strcmp()。==是简单的相等检查。因此Compare()返回一个int型,==是一个布尔型。

其他回答

Std::string::compare()返回一个int类型:

如果s和t相等,它等于0, 如果s小于t,则小于0, 如果s大于t,则大于0。

如果你想让你的第一个代码片段与第二个代码片段等效,它实际上应该是:

if (!s.compare(t)) {
    // 's' and 't' are equal.
}

相等运算符仅测试是否相等(因此得名)并返回bool类型。

要详细说明用例,如果您感兴趣的是,当两个字符串恰好不同时,它们是如何相互关联的(更小或更大),那么compare()可能很有用。PlasmaHH正确地提到了树,它也可以是,比如说,一个旨在保持容器排序的字符串插入算法,一个上述容器的二分搜索算法,等等。

编辑:正如Steve Jessop在评论中指出的那样,compare()对于快速排序和二进制搜索算法最有用。自然排序和二分搜索只能用std::less实现。

这就是标准对operator==的描述

21.4.8.2操作符= = 模板<类图表,类特征,类分配器> bool操作符==(const basic_string<charT,traits,Allocator>& lhs, const basic_string<charT,traits,Allocator>& rhs) 返回:lhs.compare(rhs) == 0。

看起来没有太大的区别!

如果只是想检查字符串是否相等,可以使用==运算符。确定两个字符串是否相等比查找排序(这是compare()给出的)更简单,因此在您的情况下,使用相等操作符可能性能更好。

更长的回答:API提供了一个检查字符串是否相等的方法和一个检查字符串顺序的方法。您需要字符串相等,因此使用相等操作符(以便您的期望与标准库实现者的期望一致)。如果性能很重要,那么您可能希望测试这两种方法并找出最快的方法。

Compare()等价于strcmp()。==是简单的相等检查。因此Compare()返回一个int型,==是一个布尔型。

Suppose consider two string s and t. Give them some values. When you compare them using (s==t) it returns a boolean value(true or false , 1 or 0). But when you compare using s.compare(t) ,the expression returns a value (i) 0 - if s and t are equal (ii) <0 - either if the value of the first unmatched character in s is less than that of t or the length of s is less than that of t. (iii) >0 - either if the value of the first unmatched character in t is less than that of s or the length of t is less than that of s.