非修改性序列算法之count和count_if

本文介绍C++ STL中count与count_if函数的使用方法,包括两种格式及其实例演示。第一种格式用于统计指定元素出现次数,第二种格式通过条件函数统计满足条件的元素个数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

count主要用来统计容器内元素个数,其格式有两种:

第一种,第三个参数为元素值

template<class _InIt,
    class _Ty> inline
    typename iterator_traits<_InIt>::difference_type
        count(_InIt _First, _InIt _Last, const _Ty& _Val)

第二种,第三个参数为条件函数:

template<class _InIt,
    class _Pr> inline
    typename iterator_traits<_InIt>::difference_type
        count_if(_InIt _First, _InIt _Last, _Pr _Pred)

程序实例:

#include<iostream>
#include<functional>
#include<algorithm>
#include<vector>

template<typename T>
int PushNum(T &vec, int first, int last) {
    int ret = 0;
    if (first > last) {
        ret = -1;
        cout << "function PushNum first > last error:" << ret << endl;
    }
    while (first <= last) {
        vec.push_back(first);
        first++;
    }
    return ret;
}

template<typename T>
void print(T &ele) {
    cout << ele << " ";
}

bool isEven(int &ele) {
    return ele % 2 == 0;
}


using namespace std;

int main(){
    vector<int> vec;
    PushNum(vec, 1, 10);
    for_each(vec.begin(), vec.end(), print<int>);
    cout << endl;
    int count1 = count(vec.begin(), vec.end(), 5);
    int count2 = count_if(vec.begin(), vec.end(), isEven);
    int count3 = count_if(vec.begin(), vec.end(), bind2nd(greater<int>(), 2));
    cout << count1 << endl;
    cout << count2 << endl;
    cout << count3 << endl;
    system("pause");
    return 0;
}

输出结果:

这里写图片描述

第一个count是求元素值等于5的个数,第二个count是求满足偶数的个数,第三个count是求大于2的个数。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值