Get an iterator to the n’th element of a vector in C++

In this post, we will discuss how to get an iterator to the n’th element of a vector in C++.

 

1. Using std::advance

To get an iterator starting from the n’th item, the idea is to construct an iterator pointing to the beginning of the input vector and call standard algorithm std::advance to advance the iterator by specified positions.

 

Download   Run Code

Output:

4 5

 

2. Using + operator

We can also set the starting iterator in single line using + operator as shown below. This works as std::vector has random-access iterators and we can do pointer arithmetic on them.

 

Download   Run Code

Output:

4 5

 

3. Skipping elements inside the loop

Another solution is to use the normal for-loop to iterate the vector and skip the first n elements inside the loop as shown below:

 

Download   Run Code

Output:

4 5

 
Thanks for reading.

Please use our online compiler to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 



Leave a Reply

avatar
  Subscribe  
Notify of