Iterate from second element of a vector in C++
This post will discuss how to iterate from the second element of a vector in C++. Assume the vector is not empty.
1. Using std::advance
function
A simple solution is to get an iterator to the beginning of the vector and use the STL algorithm std::advance
to advance the iterator by one position. Then we use that iterator as the starting position in the loop.
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 }; std::vector<int>::iterator it = v.begin(); std::advance(it, 1); // or, use `++it` while (it != v.end()) { std::cout << *it << ' '; ++it; } return 0; } |
Output:
2 3 4 5
2. Using std::next
or ++
, +
operator
We can even set the starting iterator in a single line using any of the following methods:
⮚ Using std::next
in C++11
1 2 3 |
for (auto it = std::next(v.begin()); it != v.end(); ++it) { std::cout << *it << ' '; } |
⮚ Using ++
operator
1 2 3 |
for (auto it = ++v.begin(); it != v.end(); ++it) { std::cout << *it << ' '; } |
⮚ Using +
operator
1 2 3 |
for (auto it = v.begin() + 1; it != v.end(); ++it) { std::cout << *it << ' '; } |
3. Skipping the first element inside the loop
The idea is to use a normal for-loop to iterate the vector and skip the first element inside the loop, as shown below:
1 2 3 4 5 6 |
for (auto it = v.begin(); it != v.end(); ++it) { if (it != v.begin()) { std::cout << *it << ' '; } } |
That’s all about iterating from the second 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 :)