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

1. Using std::advance function

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 the 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 a single line using the + 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

That’s all about getting an iterator to the nth element of a vector in C++.