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

1. Using std::find

The C++ standard library offers the std::find function which returns an iterator to the first matching element in the specified range, or an iterator to the end of the sequence if the element is not found. It can be used as follows to find the index of a value in an array in C++:

Download  Run Code

Output:

Element found at index 3

 
The above solution uses std::distance to find the distance between iterators. We can also apply the pointer arithmetic to get the required index.

Download  Run Code

Output:

Element found at index 3

2. Using Custom Routine

We can also implement our custom function to return the index of the first occurrence of the specified element in an array. The idea is to perform a linear search on the array using a regular for loop, and terminate the search on the first matching item. If the array is sorted, we can use the binary search algorithm.

Download  Run Code

Output:

Element found at index 3

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