跳转到主内容
趣航编程网 - 趣学编程,启航技术之路!

C++如何使用std::all_of, any_of, none_of?(算法示例)

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 中是否所有数都是正数 go语言参考手册 中文CHM版 Go 是一个开源的编程语言,它能让构造简单、可靠且高效的软件变得容易。本文给大家带来Go参考手册,需要的可以来下载! Go是从2007年末由Robert Griesemer, Rob Pike, Ken Thompson主持开发,后来还加入了Ian Lance Taylor, Russ Cox等人,并最终于2009年11月开源,在2012年早些时候发布了Go 1稳定版本。现在Go的开发已经是完全开放的,并且拥有一个活跃的社区。 Go 语言特色 简洁、快速、安全 并行、有趣、开源 内存管理、v数组安全、编译 下载
#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::vector nums = {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(std::isdigit)
避免重载歧义(C++20 起部分 标准库 已优化) 算法复杂度均为 O(n),最坏遍历全部元素;
any_of
和
all_of
可能提前退出(短路) 对
std::initializer_list
也适用:
std::all_of({1,2,3}, [](int x){return x>0;})

相关文章