对于空输入字符串,string::find的行为是否定义良好?
c++: Is the behavior of string::find for empty input string well defined
下面的代码片段在我的编译器(visual studio)上总是返回true。但是这种行为定义良好并且可移植吗?
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
}
我发现cppreference.com比标准网站更容易阅读。引用:
查找第一个子字符串等于
str
…形式上,如果满足以下所有条件,则子串
str
在位置xpos
上被找到:
xpos >= pos
xpos + str.size() <= size()
- 适用于
str
,Traits::eq(at(xpos+n), str.at(n))
中所有位置n
空字符串总是匹配目标字符串的开头,因为
- 0>= 0
- 0+0 <= size()
- 没有位置是
str
,所以匹配条件为空真。
是:"当且仅当pos <= size()时在pos处找到空子字符串"
根据Cppreference:
- 当且仅当pos <= size()
str.find("")
使用std::basic_string::find
的第三个重载,其签名为:
size_type find( const CharT* s, size_type pos = 0 ) const;
这意味着pos
从0
开始,所以pos <= size()
总是为真。
相关文章:
- 在提升multi_index容器中,是否定义了"default index"?
- sprintf(b, "%" ) 是否定义了?
- 重载虚拟行为是否定义良好?
- 它是否定义了哪些算法可以接受可变 lambda 的实现?
- 如何检查是否定义了固定宽度的整数
- &*NULL 在C++中是否定义良好?
- C++标准是否定义了结构中成员函数的函数内定义是否必须具有静态链接?
- 将以"_[a-z0-9]"开头和"using"的标识符导入全局命名空间是否定义良
- SFINAE 检测是否定义了类型
- 标准是否定义了共同基础?
- 根据是否定义了另一个宏来评估宏
- 获取未初始化对象成员的地址是否定义良好?
- 如何测试是否定义了结构的成员 (c++)
- 如何测试标准库中是否定义了 std::remove_cvref
- 对非活跃的工会成员使用"std::addressof"是否定义明确
- C++模板 - 几个专业 - 行为是否定义?
- 如何检查是否定义了标头保护
- C++14 是否定义了无符号 int 的填充位上的按位运算符的行为
- C / C++中无符号整数的减法和比较是否定义良好?
- 在比较中使用已强制转换为另一种类型的函数指针是否定义良好?