This post provides an overview of available methods to find an index of the first occurrence of an element in the array in C++.

1. Naive solution

A simple solution is to write our own custom routine for finding the index of the first occurrence of an element. The idea is to perform a linear search on the given array for determining the index. This approach is demonstrated below:

Download  Run Code

Output:

Element 2 is present at index 3 in the given array

2. Using std::find algorithm

We can also use the std::find algorithm, which returns an iterator that points to the target value. It is defined in the <algorithm> header. To get the required index, apply pointer arithmetic, or make a call to std::distance.

Download  Run Code

Output:

Element 2 is present at index 3 in the given array

3. Using std::find_if algorithm

Sometimes it is desired to search for an element that meets certain conditions in the array. For instance, find the index of the first 2-digit number in the array. The recommended approach is to use the std::find_if algorithm, which accepts a predicate to handle such cases.

Download  Run Code

Output:

Element 2 is present at index 3 in the given array

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