std::all_of、any_of、none_of是C++11引入的逻辑谓词算法,均接受迭代器范围和一元谓词,返回bool值:all_of要求所有元素满足条件(空区间为true),any_of要求至少一个满足(空区间为false),none_of要求全不满足(空区间为true)。

std::all_of、any_of、none_of 是 C++11 引入的三个常用算法,定义在 头文件中,用于对容器(或迭代器范围)中的元素进行**逻辑谓词判断**,返回 bool 值。它们简洁高效,替代手写循环,语义清晰。
核心用法:传入范围 + 谓词函数
三者签名一致:
bool all_of(InputIt first, InputIt last, UnaryPredicate pred); bool any_of(InputIt first, InputIt last, UnaryPredicate pred); bool none_of(InputIt first, InputIt last, UnaryPredicate pred);
参数说明:
-
first,last:左闭右开区间[first, last),支持任意输入迭代器(如vector::begin(),array::cbegin()) -
pred:一元谓词,即接受一个元素并返回bool的可调用对象(lambda、函数指针、函数对象等)
std::all_of:是否所有元素都满足条件?
仅当区间内每个元素都使谓词返回 true 时返回 true;空区间返回 true(逻辑上“全真”在空集成立)。
立即学习“C++免费学习笔记(深入)”;
示例:检查 vector 中是否所有数都是正数
#include#include #include std::vector v = {2, 4, 6, 8}; bool all_positive = std::all_of(v.begin(), v.end(), [](int x) { return x > 0; }); // → true std::vector w = {−1, 3, 5}; bool all_even = std::all_of(w.begin(), w.end(), [](int x) { return x % 2 == 0; }); // → false(−1 不是偶数)
std::any_of:是否存在至少一个元素满足条件?
只要有一个元素使谓词返回 true 就返回 true;空区间返回 false。
示例:检查是否有负数、是否有字母(string)
std::vectornums = {1, −5, 3}; bool has_negative = std::any_of(nums.begin(), nums.end(), [](int x) { return x < 0; }); // true std::string s = "Hello123"; bool has_digit = std::any_of(s.begin(), s.end(), ::isdigit); // true(::isdigit 是 C 风格函数指针)
std::none_of:是否没有任何元素满足条件?
等价于 !std::any_of(...),但语义更直接:所有元素都使谓词返回 false 时才为 true;空区间返回 true。
示例:检查字符串是否不含空格、vector 是否无零值
std::string line = "no space here";
bool no_space = std::none_of(line.begin(), line.end(), [](char c) { return c == ' '; }); // true
std::vector data = {1, 2, 3, 4};
bool no_zero = std::none_of(data.begin(), data.end(), [](int x) { return x == 0; }); // true
实用技巧与注意事项
- 谓词可以捕获外部变量(用 lambda),例如检查是否所有元素都大于某个阈值:
[threshold](int x) { return x > threshold; } - 支持 C 风格函数(如
std::isupper、std::isdigit),但需注意命名空间——推荐用::toupper或显式static_cast避免重载歧义(C++20 起部分标准库已优化)(std::isdigit) - 算法复杂度均为 O(n),最坏遍历全部元素;
any_of和all_of可能提前退出(短路) - 对
std::initializer_list也适用:std::all_of({1,2,3}, [](int x){return x>0;})










