C++中xpos和迭代器的关系是什么

问题描述

假设xposstd::basic_string::find类型的size_type的返回对象,我们可以使用xpos通过{{1}访问std::string中的字符}},而some_string[xpos]本身可以用来表示一个字符在字符串中的索引,我们也可以直接打印一个xpos

xpos

我们也可以使用 std::string s{"012345678902"}; auto res = s.find('2'); std::cout << s[res] << " at " << res << '\n'; >>> 2 at 2 来访问带有运算符 iterator 的容器中的项目,但是 我们不能直接打印一个 *,我们需要使用 iterator 来计算索引。据我了解,std::distancexpos 在某种程度上是相似的,但绝对不是一回事。但是,当我使用 iterator 时,https://en.cppreference.com/w/cpp/string/basic_string/erase 明确表示我们需要两个 std::basic_string::erase(iterator first,iterator last) 才能删除 iterators

范围内的所有字符
[first,last)

这按预期工作。但是当我用两个 std::string s{"012345678902"}; auto it = std::find(s.begin(),s.end(),'0'); auto rit = std::find(s.rbegin(),s.rend(),'0'); s.erase(it,rit.base()-1); std::cout << s << '\n'; >>> 02 替换上面的 xposit

rit

代码std::string s{"012345678902"}; s.erase(s.find('0'),s.find_last_of('0')); std::cout << s << '\n'; >>> 02 版本一样有效。这让我很困惑,既然 iteratorxpos 不相同,为什么 iterator 可以完美地代替 xpos 函数中的 iteratorstd::basic_string::erase(iterator first,iterator last)xpos 之间究竟是什么关系?

解决方法

在这两个调用中,xpositerator 之间没有关系。您只是调用了不同的 erase 重载,特别是:

constexpr basic_string& erase( size_type index = 0,size_type count = npos );

请注意,您似乎得到了相同的结果,因为

中的第一个参数
s.erase(s.find('0'),s.find_last_of('0'));

实际上是第 0 个位置,因为第 0 个索引是字符 '0'

一般来说,将 xpos 传递给这个重载的第二个参数是没有意义的,因为它需要一个“计数”,而不是“位置”。如果您想真正擦除第一个和最后一个 '0' 之间的所有内容,您可以这样写:

auto xp = s.find('0'); 
s.erase(xp,s.find_last_of('0') - xp);