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.

A. K.
  • 34,395
  • 15
  • 52
  • 89
  • Possible duplicate of [C++ STL Vectors: Get iterator from index?](http://stackoverflow.com/questions/671423/c-stl-vectors-get-iterator-from-index) – Simon Featherstone Oct 25 '16 at 12:40

2 Answers2

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);
Cory Nelson
  • 29,236
  • 5
  • 72
  • 110
  • thanks... rite now just adding 10 works for me. But i'll take note for the advance. – A. K. Aug 04 '11 at 02: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 Aug 04 '11 at 03: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 Aug 04 '11 at 03: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 http://stackoverflow.com/questions/2152986/best-way-to-get-the-index-of-an-iterator?rq=1 – underscore_d Nov 16 '15 at 21:03
44

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

pyroscope
  • 4,120
  • 1
  • 18
  • 13
  • 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 Nov 12 '14 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 Oct 17 '19 at 08:34