Get an iterator to n’th element of a vector in C++
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
#include <iostream> #include <vector> #include <iterator> void print(auto start, auto end) { for (auto it = start; it != end; ++it) { std::cout << *it << ' '; } } int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; int n = 3; std::vector<int>::const_iterator start = v.cbegin(); std::advance(start, n); print(start, v.cend()); return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; int n = 3; for (auto it = v.cbegin() + n; it != v.cend(); ++it) { std::cout << *it << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> v = { 1, 2, 3, 4, 5 }; int n = 3; // skip the first `n` elements inside the loop for (auto it = v.begin(); it != v.end(); ++it) { if (std::distance(it, v.begin() + n) <= 0) { std::cout << *it << ' '; } } return 0; } |
Output:
4 5
That’s all about getting an iterator to the nth element of 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 :)