我刚刚阅读了一些关于使用的建议
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/