std::ranges::none_of()
is a powerful algorithm for checking if none of the elements in a range meet a specific condition. Here are some real-world examples where this can be useful:
In form validation, you might want to check that none of the input fields are empty:
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
int main() {
std::vector<std::string> fields{
"username", "password", "email"};
auto isEmpty = [](const std::string& field) {
return field.empty();
};
bool allFieldsFilled = std::ranges::none_of(
fields, isEmpty);
std::cout << "All fields filled: "
<< (allFieldsFilled ? "Yes" : "No");
}
All fields filled: Yes
Ensure no user in a list has administrative privileges:
#include <algorithm>
#include <iostream>
#include <vector>
class User {/*...*/};
int main() {
std::vector<User> users {
User{"Alice", false},
User{"Bob", false},
User{"Charlie", false}
};
bool noAdmins = std::ranges::none_of(
users, &User::hasAdminRights);
std::cout << "No admin users: "
<< (noAdmins ? "Yes" : "No");
}
No admin users: Yes
Check that no values in a dataset are negative:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> data {10, 20, 30, 40, 50};
auto isNegative = [](int value) {
return value < 0;
};
bool allPositive = std::ranges::none_of(
data, isNegative);
std::cout << "All values positive: "
<< (allPositive ? "Yes" : "No");
}
All values positive: Yes
Using std::ranges::none_of()
helps keep your code clean, expressive, and efficient, making it easier to implement and maintain real-world software solutions.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to the 5 main counting algorithms in the C++ standard library: count()
, count_if()
, any_of()
, none_of()
, and all_of()