问题描述
我可以假设给定
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()
确实,评论说,如果您切换到使用
。但是,这与您的原始问题不直接相关,我99%确定您不会切换到std :: wstring
而不是std :: string
==
甚至不会编译,因为你不能比较wchar_t
code> charstd :: 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 forbasic_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 ofstd::string
, then==""
won't even compile, because you can't compare a string ofwchar_t
with one ofchar
. This, however, is not directly relevant to your original question, and I am 99% sure you will not switch tostd::wstring
.这篇关于C ++:is string.empty()总是等效于string =="" ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!