本文介绍了C ++:is string.empty()总是等效于string =="&quot ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以假设给定

  std :: string str; 
... // do something to str

以下语句总是为真吗?

 (str.empty()==(str ==))


解决方案

回答



下面是 bits / basic_string.h 的相关实现, basic_string

  / ** 
*如果%string为空,则返回true。等同于* this ==。
* /
bool
empty()const
{return this-> size()== 0; }



讨论



形式对 std :: string 是等效的,您可以 希望使用 .empty()



确实,评论说,如果您切换到使用 std :: wstring 而不是 std :: string ==甚至不会编译,因为你不能比较 wchar_t code> char 。但是,这与您的原始问题不直接相关,我99%确定您不会切换到 std :: wstring


Can I make an assumption that given

std::string str;
... // do something to str

Is the following statement is always true?

(str.empty() == (str == ""))
解决方案

Answer

Yes. Here is the relevant implementation from bits/basic_string.h, the code for basic_string<_CharT, _Traits, _Alloc>:

  /**
   *  Returns true if the %string is empty.  Equivalent to *this == "".
   */
  bool
  empty() const
  { return this->size() == 0; }

Discussion

Even though the two forms are equivalent for std::string, you may wish to use .empty() because it is more general.

Indeed, J.F. Sebastian comments that if you switch to using std::wstring instead of std::string, then =="" won't even compile, because you can't compare a string of wchar_t with one of char. This, however, is not directly relevant to your original question, and I am 99% sure you will not switch to std::wstring.

这篇关于C ++:is string.empty()总是等效于string ==&quot;&quot ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-19 14:33
查看更多