In this article, we will discuss different ways to check if all elements in a vector are equal or not.
Table Of Contents
Method 1: Using STL Algorithm all_of()
In C++, the STL algorithm provides a function all_of(), to check if a predicate is true for all the elements of a sequence.
We can pass the start, and end iterators of a vector to the all_of() function, along with a lambda function as predicate. In this lambda function, we will check if the given element is equal to the first element of vector or not. If this lambda function
returns true for all the elements of vector/range, then it means all elements of vector are equal. Let’s see an example,
#include <vector> #include <iostream> #include <algorithm> using namespace std; // check if all elements of a vector are equal template <typename T> bool all_equal(const vector<T>& vecObj) { return all_of( vecObj.begin(), vecObj.end(), [&](const T& value){ return value == *(vecObj.begin()); }); } int main() { vector<int> vecObj {11, 11, 11, 11, 11}; if( all_equal(vecObj)) { cout<<"All elements of vector are equal \n"; } else { cout<<"All elements of vector are not equal \n"; } return 0; }
Output:
All elements of vector are equal
Method 2: Using for-loop
Iterate over all elements of vector using a for loop, and for each element check if it is equal to the first element of vector or not. If any element is not equal to the first element, then break the loop, because it means all elements in vector are not equal. Let’s see an example
#include <vector> #include <iostream> #include <algorithm> using namespace std; // check if all elements of a vector are equal template <typename T> bool all_values_equal(const vector<T>& vecObj) { bool result = true; for (const auto& value : vecObj) { if(value != *(vecObj.begin())) { result = false; break; } } return result; } int main() { vector<int> vecObj {11, 11, 11, 11, 11}; if( all_values_equal(vecObj)) { cout<<"All elements of vector are equal \n"; } else { cout<<"All elements of vector are not equal \n"; } return 0; }
Output:
Frequently Asked:
- Check if a vector is sorted in C++
- How to compare two vectors in C++
- vector::insert() function in C++
- Convert a String to a Vector of Bytes in C++
All elements of vector are equal
Summary
We leaned about different ways to check if all elements in vector are equal.