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;
    }
    
  • 相关阅读:
    轻量级Spring定时任务(Spring-task)
    Mysql语句优化建议
    python时间日期处理
    subprocess
    Tkinter初体验
    java基础
    java JVM
    NFV
    java加载properties文件的六种方法总结
    悲观锁和乐观锁的区别
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12113194.html
Copyright © 2011-2022 走看看