C ++ string ==和compare()之间的区别? [英] Differences between C++ string == and compare()?
问题描述
我只是看一些关于使用
的建议。 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;
返回:lhs.compare(rhs)== 0。 p>
看起来没什么区别!
I just read some recommendations on using
std::string s = get_string();
std::string t = another_string();
if( !s.compare(t) )
{
instead of
if( s == t )
{
I'm almost always using the last one because I'm used to it and it feels natural, more readable. I didn't even know that there was a separate comparison function. To be more precise, I thought == would call compare().
What are the differences? In which contexts should one way be favored to the other?
I'm considering only the cases where I need to know if a string is the same value as another string.
This is what the standard has to say about 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.
Seems like there isn't much of a difference!
这篇关于C ++ string ==和compare()之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!