Bounds of std::string::find_first_of

Bounds of std::string::find_first_of

本文关键字:of first find string std Bounds      更新时间:2023-10-16

假设我有一个字符串foo,并且我想搜索第二个周期(如果有的话)。

我使用的是这个代码:

 std::size_t start = foo.find_first_of('.');
 if (start != std::string::npos){
     std::size_t next = foo.find_first_of('.', start + 1);
     /*and so on*/

如果第一个句点在字符串的末尾,我想知道这是否定义良好。

我认为这是因为start + 1将在null终止符上,所以我没有访问任何不应该访问的内存的危险。

我说得对吗?

如果第一个点在字符串的末尾,则它位于索引size() - 1

那么start + 1 == size(),这意味着find_first_of将在区间[size(), size())中查找。这是一个空间隔,因此根本不会进行内存访问。

在这一点上很可能没有null终止符。(标准不保证:c_str()需要增加一个)。

但是你的代码在任何情况下都是好的。将指针设置为指向1-ast-an-array的行为是明确定义的,因此允许使用start + 1调用函数,因为start是字符串中的最后一个字符。在内部,如果位于find_first_of将搜索的区域之外,则不会对该指针进行取消引用

C++标准不对第二个参数的值施加任何限制。

该函数试图通过以下方式计算实际位置xpos

pos <= xpos and xpos < size()

如果找不到这样的速度,则返回std::string::npos

例如

std::string s( "AB" );
auto pos = s.find_first_of( "A", std::string::npos );
if ( pos == std::string::npos ) std::cout << "Not found" << std::endl;

输出为

Not found