ICode9

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

c++ algorithm之all_of

2021-02-23 20:32:06  阅读:207  来源: 互联网

标签:std last 函数 algorithm pred 元素 c++ first


函数原型:

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

作用:
对[first,last)范围内的所有元素进行pred操作,如果pred都返回true,则all_of函数返回true,如果范围为空则返回false.
函数的行为类似与下面函数
template<class InputIterator, class UnaryPredicate>
  bool all_of (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  while (first!=last) {
    if (!pred(*first)) return false;
    ++first;
  }
  return true;
}

 

函数参数:

first,last

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

pred

一元函数接受一个序列范围内的元素,返回一个可以转换为bool的值。函数的返回值反应了元素是否满足pred检测的情况。函数内部不应该

修改函数参数。这项只能是函数指针或者函数对象。

 

返回值

返回true表示范围内的所有元素都满足pred要求,范围为空时返回false,其他情况也返回false。

 

// all_of example
#include <iostream>     // std::cout
#include <algorithm>    // std::all_of
#include <array>        // std::array

int main () {
  std::array<int,8> foo = {3,5,7,11,13,17,19,23};

  if ( std::all_of(foo.begin(), foo.end(), [](int i){return i%2;}) )
    std::cout << "All the elements are odd numbers.\n";

  return 0;
}

 

ouput:

All the elements are odd numbers.

 

时间复杂度:

O(n)

 

异常情况:

两种情况会抛出异常,一种时pred,另一种操作迭代器不当。 无效的参数会导致未定义的行为。

标签:std,last,函数,algorithm,pred,元素,c++,first
来源: https://www.cnblogs.com/haideshiyan35/p/14433981.html

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

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

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

ICode9版权所有