【STL】非变异算法之计数

这篇博客深入探讨了C++ STL中用于计数的`count`和`count_if`算法,通过实例分析了它们的用法和应用场景。
摘要由CSDN通过智能技术生成

本博文主要讲解了count count_if 的使用

  1. 实例
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
    int a[] = {1,2,3,4,5,6,6,7,8,9};
    int len = sizeof(a)/sizeof(int);
    cout<<"请输入你想查询的数:"<<endl;
    int wantNum;
    cin>>wantNum;
    int nCount = count(a,a+len,wantNum);
    cout<<wantNum<<"出现的次数为:"<<nCount<<endl;
    system("pause");
    return 0;
}

2.实例2


/*
*【1】查询有多少学生成绩为80
*【2】查询有多少学生成绩大于80
*【3】查询有多少学生成绩小于80
*/
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
using namespace std;
class student 
{
public:
    int stdno;
    string strName;
    int grade;
    student(int stdno,string strName,int grade)
    {
        this->stdno = stdno;
        this->strName = strName;
        this->grade = grade;
    }
    bool operator==(int grade)
    {
        return this->grade == grade;
    }
};
//
class macthExpress
{
    int grade;
public:
    macthExpress(int grade)
    {
        this->grade = grade;
    }
    bool operator() (student s)
    {
        return s.grade > grade;
    }
};
class macthExpressLow
{
    int grade;
public:
    macthExpressLow(int grade)
    {
        this->grade = grade;
    }
    bool operator() (student s)
    {
        return s.grade < grade;
    }
};
int main()
{
    vector<student>stdVec;
    student s1(1,"lijia",100);
    student s2(2,"renyin",60);
    student s3(3,"zhangchen",90);
    student s4(4,"xiaodeguang",80);
    student s5(5,"weiyimeng",80);
    stdVec.push_back(s1);
    stdVec.push_back(s2);
    stdVec.push_back(s3);
    stdVec.push_back(s4);
    stdVec.push_back(s5);

    ///等于80分的个数
    int nCount = count(stdVec.begin(),stdVec.end(),80);
    cout<<"分数等于80分的有"<<nCount<<"个"<<endl;

    //大于80分的个数
    nCount = count_if(stdVec.begin(),stdVec.end(),macthExpress(80));
    cout<<"大于80分的个数:"<<nCount<<endl;

    //小于80分的个数
    nCount = count_if(stdVec.begin(),stdVec.end(),macthExpressLow(80));
    cout<<"小于80分的个数:"<<nCount<<endl;
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值