C++ STL transform 函数说明

说明

简而言之,transform是用来做转换的。
转换有两种:一元转换和二元转换。

一元转换是对容器给定范围内的每个元素做某种一元运算后放在另一个容器里。只涉及一个参与转换运算的容器。
有4个参数,前2个指定要转换的容器的起止范围,第3个参数是结果存放容器的起始位置,第4个参数是一元运算。
函数签名是:

template< class InputIt, class OutputIt, class UnaryOperation >
OutputIt transform( InputIt first1, InputIt last1, OutputIt d_first,
                    UnaryOperation unary_op );

二元转换是对两个容器给定范围内的每个元素做二元运算后放在另一个容器里。涉及两个参与转换运算容器。
有5个参数,前2个指定参与转换的第1个容器的起止范围,第3个参数是转换的第2个容器的起始位置,
第4个参数是结果存放容器的起始位置,第5个参数是二元运算。
函数签名是:

template< class InputIt1, class InputIt2, class OutputIt, class BinaryOperation >
OutputIt transform( InputIt1 first1, InputIt1 last1, InputIt2 first2, 
                    OutputIt d_first, BinaryOperation binary_op );

头文件

#include <algorithm>

例子:对字符串进行大小写转换

#include <iostream>
#include <cctype>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    std::string str = "Hello, World!";
    cout << str << endl;

    // toupper
    std::string strUpper(str.length(), ' ');
    std::transform(str.begin(), str.end(), strUpper.begin(), std::toupper);
    cout << strUpper << endl;

    // tolower
    std::transform(str.begin(), str.end(), str.begin(), std::tolower);
    cout << str << endl;

    system("pause");
    return 0;
}

结果:

Hello, World!
HELLO, WORLD!
hello, world!

这是一元转换。

例子:两个数组元素分别相加

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

int main()
{
    std::vector<int> v1 = {10, 20, 30, 40, 50};
    std::vector<int> v2 = { 1, 2, 3, 4, 5 };

    std::vector<int> result(5);
    std::transform(v1.begin(), v1.end(), v2.begin(), result.begin(), std::plus<int>());

    for (int i : result) {
        std::cout << i << "\t";
    }
    std::cout << std::endl;

    return 0;
}

结果:

11      22      33      44      55

这是二元转换。

参考

http://www.cplusplus.com/reference/algorithm/transform/
https://zh.cppreference.com/w/cpp/algorithm/transform

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容