This post will discuss how to find the index of the first occurrence of a given element in vector in C++.

1. Using std::find with std::distance function

The simplest solution is to use the std::find algorithm defined in the <algorithm> header. The idea is to get the index using std::distance on the iterator returned by std::find, which points to the found value. We can also apply pointer arithmetic to the iterators. Therefore, the - operator would also work.

Download  Run Code

Output:

Element present at index 2

2. Using std::find_if with std::distance function

We can also use the standard algorithm std::find_if, which accepts a predicate. This is the recommended approach if the search needs to satisfy certain conditions. For example, finding the index of the first string starting with some character in a vector of strings.

Download  Run Code

Output:

Element present at index 2

3. Naive Solution

Finally, we can write our own routine for this, as demonstrated below:

Download  Run Code

Output:

Element present at index 2

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