• C++ STL之count函数


    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)。这题很简单,所以我们很快就可以写出代码:

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #include <vector>
     5 using namespace std;
     6 int main()
     7 {
     8     int n;
     9     vector <int> V;
    10     cin>>n;
    11     for(int i=0;i<n;i++)
    12     {
    13         int temp;
    14         cin>>temp;
    15         V.push_back(temp);
    16     }
    17     int ask;
    18     while(cin>>ask)
    19     {
    20         int num=count(V.begin(),V.end(),ask);
    21         cout<<num<<endl;
    22     }
    23     return 0;
    24 }

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

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

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

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

     1 #include <iostream>
     2 #include <cstdio>
     3 #include <algorithm>
     4 #include <vector>
     5 using namespace std;
     6 bool comp(int num)
     7 {
     8     return num%2;
     9 }
    10 int main()
    11 {
    12     vector <int> V;
    13     for(int i=1;i<=10;i++)
    14         V.push_back(i);
    15     cout<<count_if(V.begin(),V.end(),comp)<<endl;
    16     return 0;
    17 }

    例:

     1 //统计成绩大于90
     2 
     3 #include <iostream>
     4 #include <cstdio>
     5 #include <cstring>
     6 #include <vector>
     7 #include <algorithm>
     8 using namespace std;
     9 struct student
    10 {
    11     string name;
    12     int score;
    13 };
    14 bool compare(student a)
    15 {
    16     return 90<a.score;
    17 }
    18 int main()
    19 {
    20     int n;
    21     cin>>n;
    22     vector<student> V;
    23     for(int i=0;i<n;i++)
    24     {
    25         student temp;
    26         cin>>temp.name>>temp.score;
    27         V.push_back(temp);
    28     }
    29     cout<<count_if(V.begin(),V.end(),compare)<<endl;
    30     return 0;
    31 }

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

  • 相关阅读:
    ORACLE分页SQL语句
    oracle中主键自增
    html5video初试牛刀api
    如何修改tomcat的端口号
    用Java来获取访问者真实的IP地址
    根据txt文件处理的方法总结
    CXF 做 webservice 简单例子demo
    java创建TXT文件并进行读、写、修改操作
    POJ1047 Round and Round We Go
    NYOJ305 表达式求值
  • 原文地址:https://www.cnblogs.com/jaszzz/p/12635244.html
Copyright © 2020-2023  润新知