Iterate through a vector with indices in C++
This post will discuss how to iterate through a vector with indices in C++.
1. Iterator-based for-loop
The idea is to traverse the vector using iterators. To get the required index, we can either use the std::distance function or apply the pointer arithmetic. This would translate to the code below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
#include <iostream> #include <vector> int main() { std::vector<int> vec = {5, 3, 4, 1, 7}; for (auto it = vec.begin(); it != vec.end(); it++) { int index = std::distance(vec.begin(), it); std::cout << "Element " << *it << " found at index " << index << std::endl; } return 0; } |
2. Index-based for-loop
We can simplify the above code with an index-based for-loop, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <vector> int main() { std::vector<int> vec = {5, 3, 4, 1, 7}; for (int i = 0; i < vec.size(); i++) { std::cout << "Element " << vec[i] << " found at index " << i << std::endl; } return 0; } |
3. Using Range-based for-loop
Alternatively, we can use the range-based for-loop and apply the pointer arithmetic to get the index of each element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> vec = {5, 3, 4, 1, 7}; for (int &i: vec) { int index = &i - &vec[0]; std::cout << "Element " << i << " found at index " << index << std::endl; } return 0; } |
This is equivalent to the following version using the std::for_each algorithm with lambda expressions, introduced in C++11.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> vec = {5, 3, 4, 1, 7}; std::for_each(vec.begin(), vec.end(), [&vec](int const &i) { auto index = &i - &vec[0]; std::cout << "Element " << i << " found at index " << index << std::endl; }); return 0; } |
That’s all about iterating through a vector with indices 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 :)