C++ STL Vectors: Get iterator from index?


So, I wrote a bunch of code that accesses elements in an stl vector by index[], but now I need to copy just a chunk of the vector. It looks like vector.insert(pos, first, last) is the function I want... except I only have first and last as ints. Is there any nice way I can get an iterator to these values?

5/25/2009 9:28:34 AM

Accepted Answer

Try this:

vector<Type>::iterator nth = v.begin() + index;
3/22/2009 6:42:49 PM

way mentioned by @dirkgently ( v.begin() + index ) nice and fast for vectors

but std::advance( v.begin(), index ) most generic way and for random access iterators works constant time too.

differences in usage:

std::vector<>::iterator it = ( v.begin() + index );


std::vector<>::iterator it = v.begin();
std::advance( it, index );

added after @litb notes.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow