Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get iterator to a particular position of a vector

Tags:

c++

iterator

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.

like image 743
A. K. Avatar asked Aug 04 '11 02:08

A. K.


People also ask

How do you access a specific element in a vector?

Element access: reference operator [g] – Returns a reference to the element at position 'g' in the vector. at(g) – Returns a reference to the element at position 'g' in the vector. front() – Returns a reference to the first element in the vector. back() – Returns a reference to the last element in the vector.

Is it possible to assign any value to the location pointed by the iterator?

Only accessing, no assigning: One of the biggest deficiency is that we cannot assign any value to the location pointed by this iterator, it can only be used to access elements and not assign elements.


1 Answers

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); 
like image 103
Cory Nelson Avatar answered Sep 28 '22 11:09

Cory Nelson