This post will discuss how to check if all elements of a vector are equal in C++.

1. Using std::adjacent_find

A simple solution to check if all elements of a vector are equal is using the std::adjacent_find function. It returns the first occurrence of adjacent elements that satisfies a binary predicate, or end of the range if no such pair is found.

The following solution uses std::not_equal_to<int>() as the comparison function to the std::adjacent_find function. If no pair is found that satisfies it, the array must contain equal elements.

Download  Run Code

2. Using std::equal

The std::equal algorithm is used to determine whether elements in the two ranges are equal or not. The following code compares each pair of adjacent elements using std::equal, which returns true only if all elements of a vector are equal.

Download  Run Code

3. Using std::all_of

The C++11 standard algorithm std::all_of returns true if the specified predicate holds for all elements of the specified range. To check if all elements of a vector are equal, the predicate can compare each element equals any element of the vector.

Download  Run Code

 
Here’s an equivalent version using the boost library. It uses the boost::algorithm::all_of function from the <boost/algorithm/cxx11/all_of.hpp> header.

Download Code

4. Using std::find_if

Another option is to use the standard algorithm std::find_if, which accepts a predicate and finds the first matching element in the range. The following solution uses std::bind1st to bind the std::not_equal_to<int>() comparison function to the fixed value that can be equal to any vector element.

Download  Run Code

5. Using For-loop

Finally, we can write your custom logic to check if all vector elements are equal. The code would look like below:

Download  Run Code

 
Here’s another version that compares each pair of adjacent element and return false on first non-matching pair and true if and only if all set of consecutive elements are equal.

Download  Run Code

That’s all about checking if all elements of a vector are equal in C++.