This post will discuss how to find the indices of all occurrences of an element in a vector in C++.

1. Using std::find_if

To find the indices of all occurrences of an element in a vector, we can repeatedly call the std::find_if function within a loop. The following example efficiently calls the std::find_if function, where the search for the next element begins at the previous match.

Download  Run Code

Output:

3 4 6

2. Using Loop

The idea here is to perform a linear scan of the vector and report indices of all matching elements with the target. This is demonstrated below using iterators. Note that to get the required index, std::distance is used (or apply pointer arithmetic).

Download  Run Code

Output:

3 4 6

 
We can simplify the above code with a regular for-loop:

Download  Run Code

Output:

3 4 6

That’s all about finding the indices of all occurrences of an element in a vector in C++.