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;
    }
    
  • 相关阅读:
    pytorch实现BiLSTM+CRF用于NER(命名实体识别)
    pytorch中如何处理RNN输入变长序列padding
    pytorch nn.LSTM()参数详解
    Pytorch的LSTM的理解
    转:pytorch版的bilstm+crf实现sequence label
    【Tensorflow】tf.nn.atrous_conv2d如何实现空洞卷积?膨胀卷积
    iOS iphone5屏幕适配 autosizing
    IOS文件存储小结
    IIS6_IIS7日志文件位置
    xcode中没有autoSizing的设置
  • 原文地址:https://www.cnblogs.com/codemeta-2020/p/12112594.html
Copyright © 2011-2022 走看看