To check if all elements in a range satisfy a specific condition in C++, you can use the std::all_of()
algorithm from the <algorithm>
 header.
This function returns true
if the provided predicate is satisfied by all elements in the range [first, last)
, and false
 otherwise.
Here’s an example:
#include <vector>
#include <algorithm>
#include <iostream>
int main() {
std::vector<int> numbers {2, 4, 6, 8, 10};
bool all_even = std::all_of(
numbers.begin(), numbers.end(), [](int num) {
return num % 2 == 0;
}
);
if (all_even) {
std::cout << "All numbers are even.";
} else {
std::cout << "Not all numbers are even.";
}
}
All numbers are even.
<algorithm>
header to access the std::all_of()
function.std::all_of()
: This function takes three parameters: the beginning and end of the range, and a unary predicate that returns true
for elements that satisfy the condition and false
otherwise.std::all_of()
is commonly used to validate that all elements in a container meet a certain criterion, such as checking if all numbers are positive, all strings are non-empty, or all objects in a collection have a specific property.std::all_of()
stops processing as soon as it finds an element that does not satisfy the predicate, making it efficient for large datasets where early exit can save processing time.You can check any custom condition by providing the appropriate lambda function or functor. Here’s an example checking if all elements are greater than a certain value:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers{5, 7, 9, 11};
bool all_greater_than_five = std::all_of(
numbers.begin(), numbers.end(), [](int num) {
return num > 5;
}
);
if (all_greater_than_five) {
std::cout
<< "All numbers are greater than five.";
} else {
std::cout
<< "Not all numbers are greater than five.";
}
}
Not all numbers are greater than five.
The std::all_of()
algorithm is a powerful tool for validating ranges of elements against specific conditions. It simplifies the code and enhances readability while providing efficient performance.
Whether you are validating user input, processing data, or implementing business rules, std::all_of()
can be a valuable addition to your toolkit.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterator and range-based algorithms, using examples from the standard library