C++ STL之count函数

谓词(predicate):是做某些检测的函数,返回用于条件判断的类型,指出条件是否成立。

总结:

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

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

count和count_if函数是计数函数,先来看一下count函数:

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



先看一下函数的参数:

count(first,last,value); first是容器的首迭代器,last是容器的末迭代器,value是询问的元素。



可能我说的不太详细,来看一个例题:

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



看到这道题,我们会想到使用sort+equal_range函数的配合(n的范围大约在1万---10万左右),不过n<=1000 数据量不大,所以我们可以直接使用count函数,这里我们要注意一点:count函数的复杂度是线性的,最坏情况是O(n)。这题很简单,所以我们很快就可以写出代码:

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

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



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



看一下count_if函数的参数:

count_if(first,last,value,cmp); first为首迭代器,last为末迭代器,value为要查询的元素,cmp为比较函数。

其实cmp比较函数才是整个count_if函数的核心,cmp比较函数是编程的人写的,返回值是一个布尔型,我相信看完我的例题后,就可以理解这个函数的应用。例题:统计1-10奇数的个数(我的代码):

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
bool comp(int num)
{
    return num%2;
}
int main()
{
    vector <int> V;
    for(int i=1;i<=10;i++)
        V.push_back(i);
    cout<<count_if(V.begin(),V.end(),comp)<<endl;
    return 0;
}

成绩大于90

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
struct student
{
    string name;
    int score;
};
bool compare(student a)
{
    return 90<a.score;
}
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);
    }
    cout<<count_if(V.begin(),V.end(),compare)<<endl;
    return 0;
}

原文链接: https://www.cnblogs.com/Roni-i/p/8675528.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/271521

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月14日 下午9:55
下一篇 2023年2月14日 下午9:57

相关推荐