c++ - std::string find 是否要求 pos 小于字符串大小?

标签 c++ string stl stdstring

只是阅读 21.3.6.1 basic_string::find - 没有提到 pos 参数在字符串本身的范围内。

21.3.6.1 basic_string::find

size_type find(const basic_string& str, size_type pos = 0) const;

1 Effects: Determines the lowest position xpos, if possible, such that both of the following conditions obtain:

— pos <= xpos and xpos + str.size() <= size();

— at(xpos+I) == str.at(I) for all elements I of the string controlled by str.

2 Returns: xpos if the function can determine such a value for xpos. Otherwise, returns npos.

我没看错吧?

最佳答案

规范的措辞并不要求 pos小于字符串的长度。如果pos大于字符串的长度,则不能满足条件(1)的第一部分,因为如果pos <= xpos , 然后 xpos + str.size() <= size()永远不可能是真的。结果,根据第 (2) 条,该函数将返回 npos .因此,如果索引超出范围,函数的行为仍然是完美定义的。

希望这对您有所帮助!

关于c++ - std::string find 是否要求 pos 小于字符串大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9057119/

相关文章:

C++ map 插入和查找性能和存储开销

c++ - 如何使用来自 c++ stdl 的 <chrono> 将 steady_clock 时间格式化为 HH :MM:SS. 毫秒?

c++ - 通过轻量级解析器逐行解析一个巨大的 XML 文件

c++ - C++ Cygwin 中的堆大小

c# - 将字符串转换为整数

java - 解析字符串

c++ - 如何在结构数组中自动初始化最后一项?

java - 如何从标题为全名缩写的列表生成 .txt 文件

c++ - std::list 线程 push_back、front、pop_front

c++ - 带有静态 std::vector 的内存泄漏(有点)