C++ STD Gems04

count、count_if、all_of、any_of、none_of

#include 
#include 
#include 
#include 
#include 

template
void write_to_cout(Container& container, const char* delimiter = " ")
{
    std::copy(container.begin(), container.end(),
        std::ostream_iterator(std::cout, delimiter) );
}

void test0()
{
    std::vector a = {1, 2, 3, 4, 2, 6, 7, 4, 5, 2};
    write_to_cout(a);
    std::cout << std::endl;

    //test algorithm
    std::cout << std::count(a.begin(), a.end(), 2) << std::endl;  // 计算a中元素2的个数
}

void test1()
{
    std::vector a = {1, 2, 3, 4, 2, 6, 7, 4, 5, 11, 12, 6, 10, 9};
    write_to_cout(a);
    std::cout << std::endl;

    //test algorithm
    // 统计a中偶数的个数
    std::cout << std::count_if(a.begin(), a.end(), [](int x){return x % 2 == 0;} ) << std::endl;
}

void test2()
{
    std::vector a = {2, 3, 4, 2, 6, 7, 4, 5, 11, 12, 6, 10, 9};
    write_to_cout(a);
    std::cout << std::endl;

    // test algorithm
    std::cout << std::all_of(a.begin(), a.end(), [](int a){return a < 13;}) << std::endl;  //所有元素都小于13返回true
    std::cout << std::any_of(a.begin(), a.end(), [](int a){return a < 5;}) << std::endl;  // 只要有一个元素小于5返回true
    std::cout << std::none_of(a.begin(), a.end(), [](int a){return a < 3;}) << std::endl; // 所有元素都不小于3返回ture
}

int main()
{
    test0();
    test1();
    test2();
    
    return 0;
}

你可能感兴趣的:(C++ STD Gems04)