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:

Download  Run Code

2. Index-based for-loop

We can simplify the above code with an index-based for-loop, as shown below:

Download  Run Code

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.

Download  Run Code

 
This is equivalent to the following version using the std::for_each algorithm with lambda expressions, introduced in C++11.

Download  Run Code

That’s all about iterating through a vector with indices in C++.