C ++ string ==和compare()之间的区别? [英] Differences between C++ string == and compare()?

查看:1334
本文介绍了C ++ string ==和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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆