C 寻求一个std :: string :: iterator的位置
C++ Seek a std::string::iterator to given position
是否可以安全地寻找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[]
在范围内就可以很好地定义。行为只有在范围内就不确定。
- cppcheck在const std::string[]上引发警告
- 将std::string传递给WriteConsole API
- 为std::string的某个索引赋值
- 使用 std::string () const 函数启动线程或未来
- 当我们进行一些操作时,应该使用什么'std::string'或'std::stringstream'?
- 如何更改大小(std::string)
- std::string 的对象真的可以移动吗?
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 无法从 std::string 中提取C++ Unicode 符号
- std::string 构造函数如何处理固定大小的 char[]?
- 真的没有来自 std::string_view 的 std::string 的显式构造函数吗?
- 将C++ std::string 转换为 UTF-16-LE 编码的字符串
- 重载 + 自己的类和 std::string 的运算符
- 如何使用 std::string 作为 QHash 的键?
- 将日语 wstring 转换为 std::string
- 可以从std::string继承以提供类型一致性吗
- 构造函数采用std::string_view与std::string并移动
- 在共享缓冲区内存中创建 ::std::string 对象
- std::string.size() 未知行为
- Valgrind 在 std::string::swap 中报告 SIGILL