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

8次阅读

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

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

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::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::isupperstd::isdigit),但需注意命名空间——推荐用 ::toupper 或显式 static_cast(std::isdigit) 避免重载歧义(C++20 起部分 标准库 已优化)
  • 算法复杂度均为 O(n),最坏遍历全部元素;any_ofall_of 可能提前退出(短路)
  • std::initializer_list 也适用:std::all_of({1,2,3}, [](int x){return x>0;})

星耀云
版权声明:本站原创文章,由 星耀云 2026-01-02发表,共计1837字。
转载说明:转载本网站任何内容,请按照转载方式正确书写本站原文地址。本站提供的一切软件、教程和内容信息仅限用于学习和研究目的;不得将上述内容用于商业或者非法用途,否则,一切后果请用户自负。本站信息来自网络,版权争议与本站无关。
text=ZqhQzanResources