Bounds of std::string::find_first_of
Bounds of std::string::find_first_of
假设我有一个字符串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
相关文章:
- Usages of std::move
- 使用 [] 运算符时"binding reference of type discards qualifiers"
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 具有变量Number of Arguments的std::函数的矢量
- Capacity of a deque
- Deprecation of _writeBarrier()
- constexpr begin of a std::array
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- C++ "error: invalid use of void expression"
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- C++算法标头中,为什么要使用 "!(val < *first)" ?
- 赛通"Cannot take address of memoryview slice"
- C++ Version Of Double.longBitsToDouble
- 收到错误"invalid use of non-static data member 'stu::n' "
- C++ Usage of AsyncCallback
- 错误:"Left of getValue must have class/struct/union"
- Centos7 g++ "to_string is not in a member of std"
- 在C++中使用 Catch 测试框架编译错误"error: expected ';' at end of declaration list"
- C++ 字符串迭代器"find first of"
- "Multiple definition of.." "First defined here"数据结构中的同一行中