我可以通过添加一个数字来迭代迭代器? [英] Can I increment an iterator by just adding a number?
问题描述
我可以使用迭代器进行正常计算,即只是通过添加数字增加它?
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.
推荐答案
如果迭代器是一个随机存取迭代器,这些向量的迭代器是(请参见参考)。 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
C++11 note
现在有 std :: next
和 std :: 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.
这篇关于我可以通过添加一个数字来迭代迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!