C++ any_of用法学习

转自:https://www.cnblogs.com/pandamohist/p/13854504.html,https://cplusplus.com/reference/algorithm/any_of/

1.介绍

template <class InputIterator, class UnaryPredicate>  
bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred);

区间[开始, 结束)中是否至少有一个元素都满足判断式p,只要有一个元素满足条件就返回true,否则返回true。

函数功能:

复制代码
template<class InputIterator, class UnaryPredicate>
  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {// 在区间内查找
    if (pred(*first)) return true;// 符合条件返回true
    ++first;
  }
  return false;
}
复制代码

2.例子

复制代码
// any_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::any_of
#include <array>        // std::array

int main () {
  std::array<int,7> foo = {0,1,-1,3,-3,5,-5};

  if ( std::any_of(foo.begin(), foo.end(), [](int i){return i<0;}) )
    std::cout << "There are negative elements in the range.\n";

  return 0;
}

// 输出
There are negative elements in the range.
复制代码

可能会抛出异常。 另外还有:

all_of:区间[开始, 结束)中是否所有的元素都满足判断式p,所有的元素都满足条件返回true,否则返回false。

none_of:区间[开始, 结束)中是否所有的元素都不满足判断式p,所有的元素都不满足条件返回true,否则返回false。 

 

posted @   lypbendlf  阅读(35)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
历史上的今天:
2021-06-04 二进制与十进制的转换
2020-06-04 基于DL的文本分类综述
点击右上角即可分享
微信分享提示