C++ algorithm之any_of

2021-03-01 13:28

阅读:488

标签:复杂   last   col   指针   algorithm   其他   检测   定义   异常   

 

函数原型:

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

在范围[first, last)中如果有任何元素使pred返回true,any_of函数返回true,否则any_of函数返回false。

这个函数的行为等价于如下程序:

templateclass InputIterator, class UnaryPredicate>
  bool any_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (pred(*first)) return true;
    ++first;
  }
  return false;
}

 

函数参数:

first,last

输入迭代器指向序列的开始和结束位置。[first, last)范围报错所有first到last的元素,包括first指向的元素,但是不包括last指向的元素。

pred

一元函数接受一个范围内的元素作为参数,并返回一个可以转换为bool类型的值。函数的返回值表示元素是否满足函数检测的情况。函数不应该

修改函数参数。这项可以是函数指针或者函数对象。

 

返回值:

[first, last)范围内的任何元素使pred返回true,则any_of函数返回true,其他情况返回false。

 

例子:

// any_of example
#include // std::cout
#include     // std::any_of
#include         // std::array

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

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

  return 0;
}

Output:

There are negative elements in the range.

时间复杂度:

O(n)

 

异常情况:

抛出异常的两种情况:操作pred或者操作迭代器

注意无效的参数将引起未定义的行为。

C++ algorithm之any_of

标签:复杂   last   col   指针   algorithm   其他   检测   定义   异常   

原文地址:https://www.cnblogs.com/haideshiyan35/p/14438291.html


评论


亲,登录后才可以留言!