std::string 的 compare 和 == 之间的区别

Differences between compare and == for std::string

我在两个字符串之间使用 ==std::string::compare 时得到不同的结果。

这是我正在执行的代码。

#include <iostream>
#include <string>

int main()
{
    std::string str1 = "W";
    char tmpChar = 'W';
    std::string str2(1, tmpChar);
    
    bool equalCompare = str1.compare(str2);
    bool equalSign = (str1 == str2);
    std::cout << "Compare result: " << equalCompare << std::endl;
    std::cout << "Equal sign result: " << equalSign << std::endl;
    
    return 0;
}

我想这与我的创建方式有关 str2,但这是我发现将单个字符转换为字符串的方式。

Differences between compare and == for std::string

不同之处在于它们 return。 == return 当字符串比较相等时为真,否则为假。 compare return 当 *this 在参数之前时为负整数,当字符串相等时为零,当参数在 *this 之前时为正整数。