c++ - C++ 字符串 == 和 compare() 的区别?

标签 c++ string

我刚刚阅读了一些关于使用的建议

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

if( !s.compare(t) ) 
{

而不是

if( s == t )
{

我几乎总是使用最后一个,因为我已经习惯了,它感觉自然,更易读。我什至不知道有一个单独的比较功能。 更准确地说,我认为 == 会调用 compare()。

有什么区别?在哪些情况下一种方式应该优先于另一种方式?

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

最佳答案

这就是标准对 operator==

的看法

21.4.8.2 operator==

template<class charT, class traits, class Allocator>
bool operator==(const basic_string<charT,traits,Allocator>& lhs,
                const basic_string<charT,traits,Allocator>& rhs) noexcept;

Returns: lhs.compare(rhs) == 0.

好像没有太大区别!

关于c++ - C++ 字符串 == 和 compare() 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9158894/

相关文章:

c++ - 在使用 C++ 和 qt 的实时音频服务器中,在哪里将 Wav header 添加到数据中?

java - 修剪字符串末尾的数字

android - 如何设置部分 TextView 可点击

Perl 打印格式

java - 数组长度不同,Junit 中预期长度 = 1 实际长度 = 0

java - 使用 string.split 方法读取 .csv 文件

c++ - LNK2019在visual studio中无法链接静态库

c++ - C++模板的基本问题

c++ - 闯入 vector

c++ - 如何在 OpenCL 中使用结构