This tutorial will discuss about a unique way to check if all elements in array are equal in C++.
To check if all elements of an array or equal, we will use the STL algorithm std::adjacent_find()
.
The std::adjacent_find()
function accepts 3 arguments,
- Iterator pointing to the start of a sequence.
- Iterator pointing to the end of his sequence
- One callback function which accepts 2 values as arguments and return true if both the values are not equal.
For every ith element in the array, the std::adjacent_find()
function will call the std::not_equal_to<int>()
function and pass the element at index i & (i+1). If both are not equal, then the function std::not_equal_to<int>()
returns true.
So, std::adjacent_find()
will return an iterator pointing to the first element that is differet. Then we can compare the return iterator with a pointer pointing to the end of array to check if all elements in array are equal or not.
It returned iterator points to the end of array, then it means all elements in array are equal.
Let’s see the complete example,
Frequently Asked:
- Check if all elements of Array matches a Condition in C++
- Check if All elements in Array are equal to value in C++
- Check if All elements in Array are Zero in C++
- Check If Index Exists in an Array in C++
#include <iostream> #include <algorithm> int main() { int arr[] = { 33, 33, 33, 33, 33, 33 }; // Get the size of array size_t len = sizeof(arr)/sizeof(arr[0]); // Get iterator pointing to the first element // that is not equal to its next element auto it = std::adjacent_find(arr, arr + len, std::not_equal_to<int>()); // check if iterator points to the end of array if (it == arr + len) { std::cout << "Yes, all elements in the array are equal." << std::endl; } else { std::cout << "No, all elements in the array are not equal." << std::endl; } return 0; }
Output :
Yes, all elements in the array are equal.
Summary
Today we learned about several ways to check if all elements in array are equal in C++. Thanks.