Find index of an element in an array in C++

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


 

1. Naive solution

Simple solution would be to write our own custom routine for finding the index of 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. std::find algorithm

We can also use std::find algorithm which returns an iterator that points to the target value. It 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. std::find_if algorithm

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

 

Download   Run Code

Output:

Element 2 is present at index 3 in the given array

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Leave a Reply

avatar
  Subscribe  
Notify of