This post will discuss how to check if an element exists in an array in C++.

C++ standard library offers several algorithms that can efficiently search an array for the specified element. These are discussed below in detail:

1. Using std::find

A simple and elegant solution is to use the std::find function to find a value in an array. It returns an iterator to the first occurrence of the matching element, or an iterator to the end of the range if that element is not found.

Download  Run Code

Output:

Element found

 
This is recommended approach since the algorithm stops searching as soon as a match is found. With C++11, we can pass an iterator to the beginning and end of an array to it:

Download  Run Code

Output:

Element found

 
We can also implement a generic contains() routine, which offers type-safety and works for both C-style arrays and STL containers:

Download  Run Code

Output:

Element found

2. Using any_of() function

With C++11, we can use the any_of() function that returns true if and only if the specified predicate holds for any of the elements in the specified range.

Download  Run Code

Output:

Element found

3. Using std::count

Another option is to use the standard algorithm std::count, which returns the count of elements matching a value within the specified range. This, however, performs slower than the std::find function, since it might end up traversing the complete array to get the element’s count.

Download  Run Code

Output:

Element found

 
Alternatively, we can use the std::count_if function that returns the total number of elements satisfying a predicate.

Download  Run Code

Output:

Element found

If the array is sorted, the fastest option is to use the std::binary_search algorithm. It returns true if the element is found in the specified range, and false otherwise. For an unsorted array, we can sort the array and then call the binary search routine. This, however, increases the time complexity to O(nlog(n)).

Download  Run Code

Output:

Element found

5. Using Boost

Another good alternative is to use C++ boost library. It has boost::algorithm::any_of_equal function in header <boost/algorithm/cxx11/any_of.hpp>, which returns true if any of the elements in the specified array is equal to the specified value.

Download Code

Output:

Element found

6. Using Custom Routine

Finally, we can loop through the array to linearly search for the specified element. This can be implemented as follows in C++.

Download  Run Code

Output:

Element found

That’s all about checking if an element exists in an array in C++.