zoukankan      html  css  js  c++  java
  • C++ STD Gems04

    count、count_if、all_of、any_of、none_of

    #include <iostream>
    #include <vector>
    #include <iterator>
    #include <string>
    #include <algorithm>
    
    template<typename Container>
    void write_to_cout(Container& container, const char* delimiter = " ")
    {
        std::copy(container.begin(), container.end(),
            std::ostream_iterator<typename Container::value_type>(std::cout, delimiter) );
    }
    
    void test0()
    {
        std::vector<int> 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<int> 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<int> 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;
    }
    
  • 相关阅读:
    STM32cubemx-HAL库串口断线问题
    stm32 微秒定延时问题
    JLink OB SWI 取代串口打印的方式
    英特尔神经棒使用入门-NCS2 & NCS1 -OpenVino
    计算机组成原理-第4章-4.1
    计算机组成原理-第3章-3.5
    计算机组成原理-第3章-3.4
    计算机组成原理-第3章-3.3
    Tensorflow Chapter-6
    计算机组成原理-第3章-3.2
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12113194.html
Copyright © 2011-2022 走看看