zoukankan      html  css  js  c++  java
  • C++ 元素计数 count()

    C++ 元素计数 count()

    algostuff.hpp

    #ifndef ALGOSTUFF_HPP
    #define ALGOSTUFF_HPP
    
    #include <array>
    #include <vector>
    #include <deque>
    #include <list>
    
    #include <forward_list>
    #include <set>
    #include <map>
    #include <unordered_set>
    #include <unordered_map>
    
    #include <algorithm>
    #include <iterator>
    #include <functional>
    #include <numeric>
    #include <iostream>
    #include <string>
    
    //集合中添加元素
    template <typename T>
    inline void INSERT_ELEMENTS(T& coll, int first, int last)
    {
        for (int i = first; i <= last; ++i)
        {
            coll.insert(coll.end(), i);
        }
    }
    
    //输出集合中的元素
    template <typename T>
    inline void PRINT_ELEMENTS(const T& coll, const std::string & optcstr = "")
    {
        std::cout << optcstr;
        for (auto elem : coll)
        {
            std::cout << elem << "  ";
        }
        std::cout << std::endl;
    }
    
    //输出Map中的元素
    template<typename T>
    inline void PRINT_MAPPED_ELEMENTS(const T& coll, const std::string& optcstr = "")
    {
        std::cout << optcstr;
        for (auto elem : coll)
        {
            std::cout << "[" << elem.first << "," << elem.second << "]  ";
        }
        std::cout << std::endl;
    }
    #endif // !ALGOSTUFF_HPP

    testCount.cpp

    #include "algostuff.hpp"
    
    using namespace std;
    
    int main()
    {
        vector<int> vec1;
        int num1 = 0;
        INSERT_ELEMENTS(vec1, 1, 9);
        PRINT_ELEMENTS(vec1,"vec1:    ");
    
        num1 = count(vec1.cbegin(),vec1.cend(),4);
        cout << "number of elements equal to 4:   " << num1 << endl;
        num1 = count_if(vec1.cbegin(),vec1.cend(),
            [](int elem1) {
            return elem1 % 2 == 0;
        });
    
        cout << "number of elements with even value:   " << num1 << endl;
        num1 = count_if(vec1.cbegin(),vec1.cend(),
            [](int elem1) {
            return elem1 > 4;
        });
    
        cout << "number of elements greater than 4:   " << num1 << endl;
    
        system("pause");
        return 0;
    }

    vec1: 1 2 3 4 5 6 7 8 9
    number of elements equal to 4: 1
    number of elements with even value: 4
    number of elements greater than 4: 5
    请按任意键继续. . .

    代码参考:C++标准库(第2版)

  • 相关阅读:
    防抖与节流
    两台电脑互联
    es6标签模板转义html
    vue[mini-css-extract-plugin]Conflicting order between 警告解决方式(转载)
    如何解决Windows10处于通知模式(转载)
    hexo与github page搭建博客
    缓动类型参考
    微信代扣-免密支付 开通教程
    Linux服务器安全配置
    在linux (centos)上使用puppeteer实现网页截图
  • 原文地址:https://www.cnblogs.com/herd/p/12141776.html
Copyright © 2011-2022 走看看