只是阅读 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/