前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >count_if函数的用法

count_if函数的用法

作者头像
杨鹏伟
发布2020-09-11 08:01:23
5150
发布2020-09-11 08:01:23
举报
文章被收录于专栏:ypwypw

通过下面例题我们可以更清楚的理解

代码语言:javascript
复制
#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;
}
输出:5
 

再看一个例题:输入一串学生的信息,统计出成绩大于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;
}
 
看了代码之后,理解这个函数就不难了。注意:count函数和count_if函数的复杂度是线性的,在数据量大的时候,要使用更加好的方法。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-04-13 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档