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 @ 2024-06-04 00:54  lypbendlf  阅读(4)  评论(0编辑  收藏  举报