Get an iterator to a specific position in a vector in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <vector> #include <iterator> using namespace std; int main() { vector<int> ints = { 3, 6, 1, 5, 8 }; int index; // using normal iterators index = 2; std::vector<int>::iterator it = ints.begin() + index; cout << "Element at index " << index << " is " << *it << endl; // using constant iterators index = 4; std::vector<int>::const_iterator c_itr = ints.cbegin() + index; cout << "Element at index " << index << " is " << *c_itr; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
#include <iostream> #include <vector> #include <iterator> using namespace std; int main() { vector<int> ints = { 3, 6, 1, 5, 8 }; int index; // using normal iterators index = 2; std::vector<int>::iterator it = ints.begin(); std::advance(it, index); cout << "Element at index " << index << " is " << *it << endl; // using constant iterators index = 4; std::vector<int>::const_iterator c_itr = ints.cbegin(); std::advance(c_itr, index); cout << "Element at index " << index << " is " << *c_itr; return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include <vector> #include <iterator> using namespace std; int main() { vector<int> ints = { 3, 6, 1, 5, 8 }; int index; // using normal iterators index = 2; std::vector<int>::iterator it = std::next(ints.begin(), index); cout << "Element at index " << index << " is " << *it << endl; // using constant iterators index = 4; std::vector<int>::const_iterator c_itr = std::next(ints.cbegin(), index); cout << "Element at index " << index << " is " << *c_itr; return 0; } |
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++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)