减少 begin() 迭代器,然后再次增加它

Decreasing begin() iterator and then increasing it again

本文关键字:增加 然后 begin 迭代器 减少      更新时间:2023-10-16

这样的陈述按照标准有效吗?

std::string str{"123"};
auto it = str.begin();
--it;
++it; // Does *it point to character '1' now?

我已经在 g++ 4.7.2 和 clang++ 3.5 上尝试过这个 - *it返回'1' .这是 c++11 中的标准行为吗?

不,它无效。

这是未定义的行为,因为 24.2.6 [双向迭代器] 指出--it的后置条件是结果必须是可取消引用的。正如示例中前面begin()指出的那样,不满足此条件,因此代码是非法的。

由于不需要诊断,它似乎有效,但你不能(也不应该)依赖它。