如何将迭代器获取到向量的特定位置

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

假设我有一个

std::vector<int> v
//and ...
for(int i =0;i<100;++i) 
 v.push_back(i);

现在我想要一个迭代器,比如说向量的第 10 个元素.

now i want an iterator to, let's say 10th element of the vector.

不做下面的做法

std::vector<int>::iterator vi;
vi = v.begin();
for(int i = 0;i<10;i++)
  ++vi;

因为这会破坏为向量提供随机访问迭代器的优势.

as this will spoil the advantage of having random access iterator for a vector.

推荐答案

只需将 10 添加到迭代器即可.它们旨在感觉"像指针.

Just add 10 to the iterator. They are intended to "feel" like pointers.

相关文章