36

Suppose i have a

std::vector<int> v
//and ...
for(int i =0;i<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.

1

2 Answers 2

57

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);
4
  • thanks... rite now just adding 10 works for me. But i'll take note for the advance.
    – A. K.
    Commented Aug 4, 2011 at 2:17
  • 1
    I'd prefer std::advance() since it works with any iterator; that way you aren't tied to a specific container.
    – Matt Ryan
    Commented Aug 4, 2011 at 3:11
  • @Matt : In all likelihood, if your algorithm requires nth-element access, it would be uselessly inefficient with anything other than random-access iterators anyway; so it would actually be better to use operator+ instead of std::advance and get a compiler error with the wrong iterator type.
    – ildjarn
    Commented Aug 4, 2011 at 3:38
  • upped for C++11 and generic answer, next. hadn't come across that one yet! to add to your distinction of random-access iterators - the + syntax looks nice and will catch any attempts to change to a non-random-access container, as per stackoverflow.com/questions/2152986/… Commented Nov 16, 2015 at 21:03
44

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

2
  • 1
    Don't you want to add 9? Adding 0 moves to the 1st element, Adding 1 moves to the 2nd element, ... Adding n-1 moves to the nth element.
    – CrepeGoat
    Commented Nov 12, 2014 at 18:44
  • 1
    That's misleading. You're at the first element, which has index 0, so if you add 0, you're not moving and you're still at the first element.
    – RL-S
    Commented Oct 17, 2019 at 8:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.