ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

C++ algorithm之any_of

2021-02-23 21:32:51  阅读:269  来源: 互联网

标签:last 函数 algorithm pred C++ true any first


 

函数原型:

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

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

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

template<class 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 <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;
}

Output:

There are negative elements in the range.

时间复杂度:

O(n)

 

异常情况:

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

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

标签:last,函数,algorithm,pred,C++,true,any,first
来源: https://www.cnblogs.com/haideshiyan35/p/14438291.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有