This post will discuss how to find the index of each value in a range-based for-loop in C++.

1. Using pointer arithmetic

The standard C++ range-based for-loops are not designed to get the index of each value. Since a vector stores its elements contiguously, you can easily determine the index of each element of a vector using pointer arithmetic.

Download  Run Code

Output:

Index=0, Value=6
Index=1, Value=3
Index=2, Value=5
Index=3, Value=8
Index=4, Value=7

 
Alternatively, we can maintain an explicit counter to keep track of the index for each element of a vector.

Download  Run Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

 
C++20 supports an init-statement in the range-based for-loops, which is typically a declaration of a variable with an initializer.

Download  Run Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

2. Using std::for_each

Another efficient solution is to use std::for_each with C++11 lambdas. The idea remains the same – get the index of each element of a vector using pointer arithmetic since a vector is contiguous.

Download  Run Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

 
Alternatively, we can maintain an outer variable to hold the index for each element of a vector.

Download  Run Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

 
Since C++14, we can use generalized lambda captures to define local variables in the lambda object itself. For example,

Download  Run Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

3. Using std::accumulate

Another option is to use the std::accumulate standard algorithm defined in the header file <numeric>. We can override its default operation by passing a binary function in the optional fourth parameter.

Download  Run Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

4. Using Boost.Range

If you have the boost library in your project, you may get the index of a value in a vector in a range-based for-loop with boost::adaptors::indexed.

Download Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

5. Using Range-v3 library

Finally, we can use the enumerated view of the ranges-v3 library, which forms the basis for C++20’s std::ranges. Here’s an elegant solution using ranges::views::enumerate.

Download Code

Output:

Index: 0, Value=6
Index: 1, Value=3
Index: 2, Value=5
Index: 3, Value=8
Index: 4, Value=7

That’s all about finding the index of each value in a range-based for-loop in C++.