C++ STL Vectors: Get iterator from index?

C++StlVectorIterator

C++ Problem Overview


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?

C++ Solutions


Solution 1 - C++

Try this:

vector<Type>::iterator nth = v.begin() + index;

Solution 2 - C++

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.

EDIT
differences in usage:

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

or

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

added after @litb notes.

Solution 3 - C++

Also; auto it = std::next(v.begin(), index);

Update: Needs a C++11x compliant compiler

Solution 4 - C++

You can always use std::advance to move the iterator a certain amount of positions in constant time:

std::vector<int>::iterator it = myvector.begin();
std::advance(it, 2);

Solution 5 - C++

Actutally std::vector are meant to be used as C tab when needed. (C++ standard requests that for vector implementation , as far as I know - replacement for array in Wikipedia) For instance it is perfectly legal to do this folowing, according to me:

int main()
{

void foo(const char *);

sdt::vector<char> vec;
vec.push_back('h');
vec.push_back('e');
vec.push_back('l');
vec.push_back('l');
vec.push_back('o');
vec.push_back('/0');

foo(&vec[0]);
}

Of course, either foo must not copy the address passed as a parameter and store it somewhere, or you should ensure in your program to never push any new item in vec, or requesting to change its capacity. Or risk segmentation fault...

Therefore in your exemple it leads to

vector.insert(pos, &vec[first_index], &vec[last_index]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmpenView Question on Stackoverflow
Solution 1 - C++dirkgentlyView Answer on Stackoverflow
Solution 2 - C++baydaView Answer on Stackoverflow
Solution 3 - C++Viktor SehrView Answer on Stackoverflow
Solution 4 - C++TimWView Answer on Stackoverflow
Solution 5 - C++yves BaumesView Answer on Stackoverflow