This post will discuss how to get an iterator to a particular position of a vector in C++.

1. Using + operator

Since an iterator supports the arithmetic operators + and -, we can initialize an iterator to some specific position using the (+) operator, as demonstrated below:

Download  Run Code

Output:

Element at index 2 is 1
Element at index 4 is 8

2. Using std::advance function

Another solution is to get an iterator to the beginning of the vector and then call std::advance to advance the iterator by specific elements.

Download  Run Code

Output:

Element at index 2 is 1
Element at index 4 is 8

3. Using std::next function

In C++11 and above, the recommended approach is to use std::next, which advances the specified iterator by the specific number of elements.

Download  Run Code

Output:

Element at index 2 is 1
Element at index 4 is 8

That’s all about getting an iterator to a specific position in a vector in C++.