zoukankan      html  css  js  c++  java
  • 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;
    }
  • 相关阅读:
    建站始末——(转载)
    阿里云——大神建个人网站分享(转载)
    从零开始建设个人网站
    前端资料——书籍
    【python】*与** 参数问题
    【python】python异常类型
    【python】unittest中常用的assert语句
    【性能测试】性能测试总结<四>
    【性能测试】性能测试总结<三>
    【性能测试】性能测试总结<二>
  • 原文地址:https://www.cnblogs.com/Roni-i/p/8675528.html
Copyright © 2011-2022 走看看