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

原文地址:https://www.cnblogs.com/herd/p/12141776.html