我可以通过添加一个数字来增加一个迭代器吗?

2022-01-10 00:00:00 iterator c++

我可以使用迭代器进行正常计算,即通过添加一个数字来增加它吗?

Can I do normal computations with iterators, i.e. just increment it by adding a number?

例如,如果我想删除元素 vec[3],我可以这样做吗:

As an example, if I want to remove the element vec[3], can I just do this:

std::vector<int> vec;
for(int i = 0; i < 5; ++i){
      vec.push_back(i);
}
vec.erase(vec.begin() + 3); // removes vec[3] element

它适用于我 (g++),但我不确定它是否保证有效.

It works for me (g++), but I'm not sure if it is guaranteed to work.

推荐答案

如果迭代器是随机访问迭代器就可以工作,vector的迭代器是哪个(见参考).可以使用 STL 函数 std::advance推进通用迭代器,但由于它不返回迭代器,我倾向于使用 + 如果可用,因为它看起来更干净.

It works if the iterator is a random access iterator, which vector's iterators are (see reference). The STL function std::advance can be used to advance a generic iterator, but since it doesn't return the iterator, I tend use + if available because it looks cleaner.

C++11 笔记

现在有 std::nextstd::prev,做返回迭代器,所以如果你在模板领域工作,你可以使用它们来推进通用迭代器并且仍然有干净的代码.

Now there is std::next and std::prev, which do return the iterator, so if you are working in template land you can use them to advance a generic iterator and still have clean code.

相关文章