开发者

how to get iterator to a particular position of a vector

开发者 https://www.devze.com 2023-03-24 22:26 出处:网络
Suppose i have a std::vector<int> v //and ... for(int i =0;i&开发者_开发问答lt;100;++i) v.push_back(i);

Suppose i have a

std::vector<int> v
//and ...
for(int i =0;i&开发者_开发问答lt;100;++i) 
 v.push_back(i);

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

without doing the following approach

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.


This will work with any random-access iterator, such as one from vector or deque:

std::vector<int>::iterator iter = v.begin() + 10;

If you want a solution that will work for any type of iterator, use next:

std::vector<int>::iterator iter = std::next(v.begin(), 10);

Or if you're not on a C++11 implementation, advance:

std::vector<int>::iterator iter = v.begin();
std::advance(iter, 10);


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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号