当前位置: 代码迷 >> 综合 >> STL之count和count_if函数
  详细解决方案

STL之count和count_if函数

热度:23   发布时间:2024-01-15 07:59:23.0

count和count_if函数是计数函数

count函数:
count函数的功能是:统计容器中等于value元素的个数。

先看一下函数的参数:
count(first,last,value); first是容器的首迭代器,last是容器的末迭代器,value是询问的元素。

给你n个数字(n<=1000),再给你一个数字m,问你:数字m在n个数字中出现的次数。

 

#include <cstdio>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main()
{int n;vector <int> V;    //这里vector只能为intcin>>n;for(int i=0;i<n;i++){int t;cin>>t;V.push_back(temp);}int ask;while(cin>>ask){int num=count(V.begin(),V.end(),ask);cout<<num<<endl;}return 0;
}

count_if函数

 

count_if :返回区间中满足指定条件的元素数目。

template<class InputIterator, class Predicate>

   typename iterator_traits<InputIterator>::difference_type count_if(

      InputIterator _First,

      InputIterator _Last,

      Predicate _Pred

   );

Parameters

_First 输入迭代器,指向将被搜索的区间第一个元素的位置。

_Last 输入迭代器,指向将被搜索的区间最后一个元素后面的。

_Pred 用户自定义的 predicate function object ,定义了元素被计数需满足的条件。 predicate 只带一个参数,返回 true 或 false.

Return Value

满足断言(predicate)(也称为谓词)指定条件的元素数。

Remarks

这个模板函数是书法count的泛化版本,用断言指定的条件代替等于一个指定的值。

但是,假如我们要使用STL的函数 统计1-10奇数的个数,怎么办呢?

所以,我们就需要使用count_if函数,这是一个很有用的函数,我们要重点介绍它。

看一下count_if函数的参数:
count_if(first,last,value,comp); first为首迭代器,last为末迭代器,value为要查询的元素,comp为比较函数。

我们来看一下count_if函数STL的源代码:
 

template <class InputIterator, class Predicate>ptrdiff_t count_if ( InputIterator first, InputIterator last, Predicate pred ) 
{ptrdiff_t ret=0; while (first != last) if (pred(*first++)) ++ret;return ret;
}



compare比较函数才是整个count_if函数的核心

 

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
string name;
struct student
{string name;int score;
};
bool compare(student a)  //统计姓名
{return name==a.name;
}
int main()
{int n;cin>>n;vector<student> V;for(int i=0;i<n;i++){student temp;cin>>temp.name>>temp.score;V.push_back(temp);}cin>>name;cout<<count_if(V.begin(),V.end(),compare)<<endl;return 0;
}

 总结:

count       :  在序列中统计某个值出现的次数

 

count_if   :    在序列中统计与某谓词匹配的次数

 

  相关解决方案