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

    transform、for_each

    #include <iostream>
    #include <vector>
    #include <string>
    #include <iterator>
    #include <cctype>
    #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::string a = "heLlo, WorRld";
        std::string b;
    
        write_to_cout(a);
        std::cout << std::endl;
        write_to_cout(b);
        std::cout << std::endl;
    
        //test algorithm
        std::transform(a.begin(), a.end(), std::back_inserter(b), [](char c) {return std::toupper(c);}); // 将字符串a所有字母大写插入b末尾
    
        write_to_cout(a);
        std::cout << std::endl;
        write_to_cout(b);
        std::cout << std::endl <<std::endl;
    }
    
    // 二元谓词
    void test1()
    {
        std::vector<int> a = {1, 2, 3, 4, 5, 6, 7};
        std::vector<int> b = {11, 12, 13, 14, 15, 16, 17};
        std::vector<int> c;
    
        write_to_cout(a);
        std::cout << std::endl;
        write_to_cout(b);
        std::cout << std::endl;
    
        // test algorithm
        // a中每个元素乘以2加上b中每个元素得到值存入c中
        transform(a.begin(), a.end(), b.begin(), std::back_inserter(c), [](int x, int y){return 2 * x + y;} );
        write_to_cout(c);
        std::cout << std::endl << std::endl;  
    }
    
    void test2()
    {
        std::vector<int> a = {1, 12, 31, 54, 15, 6, 27};
        std::vector<int> b = {11, 12, 13, 14, 15, 16, 17};
    
        write_to_cout(a);
        std::cout << std::endl;
        write_to_cout(b);
        std::cout << std::endl;
        //test algotirhm
        std::transform(a.begin(), a.end(), b.begin(), b.begin(), [](int a, int b){return a > b ? a : b;} );
        write_to_cout(b);
        std::cout << std::endl << std::endl;
    }
    
    void test3()
    {
        std::vector<int> a = {1, 12, 31, 54, 15, 6, 27};
    
        write_to_cout(a);
        std::cout << std::endl;
    
        // test algorithm
        //将a中元素都乘以2
        std::for_each(a.begin(), a.end(), [](int& x) {return x = 2*x;});
        write_to_cout(a);
        std::cout << std::endl << std::endl;
    }
    
    int main()
    {
        test0();
        test1();
        test2();
        test3();
    
        return 0;
    }
    
  • 相关阅读:
    获取linux内核的配置项(包含模块module)_转
    PPP或PPPOE身份验证PAP和CHAP
    iptables用法
    谁能当IBM公司的CEO?
    雷军失势小米痛哭_小米总喜欢花小钱办大事,然后就总是办不好事
    高并发TCP连接数目问题
    Linux定时任务Crontab命令详解_转
    树莓派3B+首次登陆通过网络
    tar包解压后用户名改变
    一些软件设计的原则_转
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12112594.html
Copyright © 2011-2022 走看看