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版)

  • 相关阅读:
    写一个日志类用于跟踪调试
    Delphi用QJSON解析JSON格式的数据
    Http协议访问DataSnap Rest 服务器
    由于@@ServerName等问题对SQL增量升级脚本进行补充
    自动适应屏幕分辨率
    tnsping命令解析
    delphi 提取字符中的数字
    UltraISO PE(软碟通) v9.6.2.3059 注册码
    cs编写php字符显示问题
    phpMyAdmin安装设置
  • 原文地址:https://www.cnblogs.com/herd/p/12141776.html
Copyright © 2011-2022 走看看