ICode9

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

c++ algorithm之count_if

2021-03-08 08:02:22  阅读:235  来源: 互联网

标签:count last algorithm int pred 元素 c++ first


函数原型:

template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred);

功能:

在范围内返回满足条件元素的个数。

返回范围[first, last)范围内是pred为true的元素个数。

函数的行为与以下函数相等:

template <class InputIterator, class UnaryPredicate>
  typename iterator_traits<InputIterator>::difference_type
    count_if (InputIterator first, InputIterator last, UnaryPredicate pred)
{
  typename iterator_traits<InputIterator>::difference_type ret = 0;
  while (first!=last) {
    if (pred(*first)) ++ret;
    ++first;
  }
  return ret;
}

 

参数:

first,last:

输入迭代器指向序列的初始位置和末尾位置。这使用的范围[first,last)包括了first到last的所有元素,包括first迭代器

指向的元素,但是不包括last迭代器指向的元素。

pred:

一元函数接受范围内的一个元素作为参数,并返回一个可以转换为bool的值。这返回值意味着这元素是否被函数计算

在内。该函数不应该修改它的参数。这个参数可以是一个函数指针或者函数对象。

 

返回值:

在范围[first,last)中使pred返回true的元素个数。这返回值的类型为有符号的int型。

 

例子:

// count_if example
#include <iostream>     // std::cout
#include <algorithm>    // std::count_if
#include <vector>       // std::vector

bool IsOdd (int i) { return ((i%2)==1); }

int main () {
  std::vector<int> myvector;
  for (int i=1; i<10; i++) myvector.push_back(i); // myvector: 1 2 3 4 5 6 7 8 9

  int mycount = count_if (myvector.begin(), myvector.end(), IsOdd);
  std::cout << "myvector contains " << mycount  << " odd values.\n";

  return 0;
}

输出:

myvector contains 5 odd values.

 

时间复杂度:

O(n)

标签:count,last,algorithm,int,pred,元素,c++,first
来源: https://www.cnblogs.com/haideshiyan35/p/14497728.html

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

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

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

ICode9版权所有