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;
    }
    
  • 相关阅读:
    取代iframe,实现页面中引入别的页面
    axios请求
    接口跨域
    es7,es8
    promise
    移动端开发调试工具神器--Weinre使用方法
    资本论第一卷笔记
    2018春季实习生校招面经(一)阿里篇
    linux小实验-考勤模拟程序
    在基于debian的deepin或者Ubuntu上双等号“==”和双中括号“[[]]”不能使用的真相
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12113194.html
Copyright © 2011-2022 走看看