码迷,mamicode.com
首页 > 编程语言 > 详细

泛型算法(四)之计数算法

时间:2016-01-19 10:33:22      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

1、count(InputIterator first, InputIterator last, const T& val):序列中等于给定值的元素的计数

    std::vector<int> c;
    c.reserve(10);
    //向c中添加元素
    for (int i = 0; i < 10; i++)
    {
        c.push_back(i * 0);
    }
    //计算c中元素值等于0的元素个数
    int count = std::count(c.begin(), c.end(), 0);
    //输出
    std::cout << count;
    //打印结果:10

2、count_if(InputIterator first, InputIterator last, UnaryPredicate pred):序列中满足给定谓词的元素的计数

    std::vector<int> c;
    c.reserve(10);
    //向c中添加元素
    for (int i = 0; i < 10; i++)
    {
        c.push_back(i);
    }
    //计算c中元素值大于5的元素个数
    int count = std::count_if(c.begin(), c.end(), [](int element){
        return element > 5;
    });
    //输出
    std::cout << count;
    //打印结果:4

 

泛型算法(四)之计数算法

标签:

原文地址:http://www.cnblogs.com/dongerlei/p/5141173.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!