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;
}
原文地址:https://www.cnblogs.com/codemeta-2020/p/12112594.html