STL算法之count. count_if

来源:互联网 发布:php数组最大长度限制 编辑:程序博客网 时间:2024/05/18 05:10

转接自STL算法
count(beg,end,value) 返回值为value元素个数
count_if(beg,end,Pred) 统计并返回满足谓词Pred的值个数
1.count()用法示例:

#include <iostream>#include <vector>using namespace std;//count(beg,end,value) 返回值为value元素个数void test(const vector<int> &vec){    //统计值为3的个数    cout << count(vec.begin(), vec.end(),3);}int main(){    vector<int> vec{ 1,2,3,3,4,5,6,3,7,8,3 };    test(vec);    system("pause");    return 0;}

2.count_if用法及示例:

#include <iostream>#include <vector>#include <algorithm>using namespace std;//count_if(beg,end,Pred) 统计并返回满足谓词Pred的值个数void test(const vector<int> &vec){    auto f = [](const int& value)    {        return value % 2 == 0;    };    cout << count_if(vec.begin(), vec.end(), f);}int main(){    vector<int> vec{ 1,2,3,3,4,5,6,3,7,8,3 };    test(vec);    system("pause");    return 0;}
原创粉丝点击