• 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;
    }
    
  • 相关阅读:
    一个用css写出来的下拉菜单
    oracle创建新的用户 创建序列 并生成自动自增
    Ubuntu 16.04下安装网络流量分析工具 Wireshark
    Ubuntu16.04安装PostgreSQL并使用pgadmin3管理数据库_图文详解
    http协议无状态中的 "状态" 到底指的是什么?!
    Struts2使用流程
    hibernate创建一对多映射关系
    hibernate中创建一对一映射关系
    利用Hibernate进行数据库的增删改查
    Hibernate的简单流程
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12112594.html
Copyright © 2020-2023  润新知