首页 > 编程语言 > 详细

c++ algorithm之count_if

时间:2021-03-08 09:41:10      阅读:30      评论:0      收藏:0      [点我收藏+]

函数原型:

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)

c++ algorithm之count_if

原文:https://www.cnblogs.com/haideshiyan35/p/14497728.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!