[英]c++: Is the behavior of string::find for empty input string well defined
The following code snippet returns always true on my compiler(visual studio). 以下代码片段在我的编译器(visual studio)上始终返回true。 But is this behavior well defined and portable? 但这种行为是否定义良好且可移植?
bool return_always_true(std::string const& str)
{
return str.find("") != std::string::npos;
}
int main(){
cout << boolapha << return_always_true("") << endl
<< return_always_true("oxylottl") << endl
<< return_always_true("lorem ipsum") << endl;
//true true true
}
I find cppreference.com easier to read than the standard. 我发现cppreference.com比标准更容易阅读。 Quoting them: 引用它们:
Finds the first substring equal to
str
... 找到等于str
的第一个子串...Formally, a substring
str
is said to be found at positionxpos
if all of the following is true: 形式上,如果满足以下所有条件,则称在子位置xpos
处找到子串str
:
xpos >= pos
xpos + str.size() <= size()
- for all positions
n
instr
,Traits::eq(at(xpos+n), str.at(n))
对于str
所有位置n
,Traits::eq(at(xpos+n), str.at(n))
An empty string will always match at the start of the target string because 空字符串将始终在目标字符串的开头匹配,因为
str
so the match condition is vacuously true. 没有位置是str
所以匹配条件是真空的。 是的,它是:“当且仅当pos <= size()”时才在pos处找到一个空子串
According to Cppreference : 根据Cppreference :
- an empty substring is found at pos if and only if pos <= size() 当且仅当pos <= size()时才在pos处找到空子串
str.find("")
uses the third overload for std::basic_string::find
which has a signature of : str.find("")
使用std::basic_string::find
的第三个重载,其签名为:
size_type find( const CharT* s, size_type pos = 0 ) const;
Which means that pos
starts at 0
so pos <= size()
is always true. 这意味着pos
从0
开始,因此pos <= size()
始终为 true。
Yes, the behaviour is well defined and portable. 是的,行为定义明确且便携。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.