C ++ element count count ()

C ++ element count 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>set add elements//


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: 2. 3. 1. 4. 5. 6. 7. 8. 9
Number of Elements. 4 equal to:. 1
Number of Elements with the even value:. 4
Number of Elements Within last Greater. 4:. 5
Press any key to continue.

 

Reference Code: C ++ Standard Library (2nd Edition)

 

Reference Code: C ++ Standard Library (2nd Edition)

Reference Code: C ++ Standard Library (2nd Edition)

Reference Code: C ++ Standard Library (2nd Edition)

Guess you like

Origin www.cnblogs.com/herd/p/12141776.html