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

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的个数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值