This tutorial will discuss about a unique way to check if all elements in array are equal to value in C++.
To check if all elements of array matches with a given value, we are going to use the STL algorithm std::all_of()
.
Inside STL algorithm std::all_of()
we will pass 3 arguments,
- Pointer pointing to the start of array.
- Pointer pointing to the end of array
- A Lambda function, which accepts an element as an argument and returns true if the given element is equal to a given value.
The std::all_of()
function will apply the given Lambda function on all the elements of the array. If for all the elements the lambda function returns true, then the std::all_of()
function will return true.
If there is a single element in array that is not equal to the given value, then the std::all_of()
function returns false.
Like, in the below example we will check if all the elements of array are equal to value 15.
Let’s see the complete example,
Frequently Asked:
- How to Sort an Array of structs in C++?
- Check if any element in array contains string in C++
- Find index of an element in an Array in C++
- Check if Any element in Array matches a condition in C++
#include <iostream> #include <algorithm> int main() { int arr[] = { 15, 15, 15, 15, 15 }; int value = 15; // Get the size of array size_t len = sizeof(arr)/sizeof(arr[0]); // Check if all elements of array arr are equal to a value bool result = std::all_of(arr, arr + len, [&value](bool elem){ return elem == value; }); if (result) { std::cout << "Yes, all elements of array are equal to 15." << std::endl; } else { std::cout << "No, all elements of array are not equal to 15." << std::endl; } return 0; }
Output :
No, all elements of array are not equal to 15.
Summary
Today we learned about several ways to check if all elements in array are equal to value in C++. Thanks.