C 寻求一个std :: string :: iterator的位置

C++ Seek a std::string::iterator to given position

本文关键字:std string iterator 位置 一个      更新时间:2023-10-16

是否可以安全地寻找std::string::iterator到给定位置?

std :: string :: iterator具有偏移访问操作员(操作员[]),但它存在于某些人定义为未定义的行为的类别中,例如it + 3

cplusplus.com参考

std :: string :: iterator具有偏移访问操作员(operator []),但它存在于某些人定义为未定义的行为的类别中,例如 3。

我不明白这一说法。没有这样的类别。std::basic_string<>::iterator是一个随机访问迭代器,因此您可以通过添加或从中添加或减去偏移来寻找(这与您链接到的文档一致):

auto new_it = it + offset;

未定义的是寻求超越关联容器的end()迭代器,或者在开始之前。也就是说,以下是未定义的行为:

std::string str = "hi";
auto it1 = str.begin() + 2; // OK.
assert(it1 == str.end());
auto it2 = str.begin() + 3; // UB!
// At this point we cannot assert anything about it2

我不知道您从哪里得到operator[]std::string::iterator的UB。它被定义为一个随机访问迭代器,该迭代器支持i[n]以及i + n

基于其他地方的评论,看来您正在追求绝对定位(从问题的措辞中尚不清楚)。您不能从您不知道的位置的迭代器中做到这一点,但是可以通过相对于begin()返回的迭代器(即:str.begin()[3]str.begin() + 3)来实现相同的效果。如果您没有原始的字符串方便,则可以软管。

标准迭代器的指定方式不需要参考其迭代器的容器(或其他序列);这意味着无法使用迭代器进行"绝对寻求"。您将需要从字符串中获得一个新的迭代器,以检查自己是否在范围内;类似:

std::string::iterator seek(std::string & s, size_t i) {
    return s.length() <= i ? s.end() : s.begin() + i;
}

在随机访问迭代器上算术,并且在字符串上的operator[]在范围内就可以很好地定义。行为只有在范围内就不确定。