std::transform 是 C++ 标准库中非常常用的算法之一,属于 <algorithm> 头文件。它的作用是将一个(或两个)序列中的元素通过某个函数进行变换,并将结果输出到另一个序列中


一、std::transform 作用总结

std::transform 支持以下两种形式:

单输入版本(Unary operation):

template<class InputIt, class OutputIt, class UnaryOperation>
OutputIt transform(InputIt first1, InputIt last1, OutputIt d_first, UnaryOperation unary_op);
  • [first1, last1) 区间中的每个元素应用 unary_op,并写入到从 d_first 开始的输出迭代器中。

双输入版本(Binary operation):

template<class InputIt1, class InputIt2, class OutputIt, class BinaryOperation>
OutputIt transform(InputIt1 first1, InputIt1 last1, InputIt2 first2, OutputIt d_first, BinaryOperation binary_op);
  • [first1, last1)[first2, ...) 中对应元素应用 binary_op(a, b),输出到 d_first

二、示例代码

示例1:单输入 - 所有元素平方

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

int main() {
    std::vector<int> input = {1, 2, 3, 4, 5};
    std::vector<int> output(input.size());

    std::transform(input.begin(), input.end(), output.begin(),
                   [](int x) { return x * x; });

    for (int val : output) {
        std::cout << val << " "; // 输出:1 4 9 16 25
    }
}

示例2:双输入 - 向量加法

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

int main() {
    std::vector<int> a = {1, 2, 3};
    std::vector<int> b = {4, 5, 6};
    std::vector<int> result(a.size());

    std::transform(a.begin(), a.end(), b.begin(), result.begin(),
                   [](int x, int y) { return x + y; });

    for (int val : result) {
        std::cout << val << " "; // 输出:5 7 9
    }
}

示例3:应用于字符串大小写转换

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

int main() {
    std::string text = "Hello World!";
    std::transform(text.begin(), text.end(), text.begin(),
                   [](unsigned char c) { return std::toupper(c); });

    std::cout << text << std::endl;  // 输出:HELLO WORLD!
}

三、使用注意事项

  1. output 容器需要提前分配好空间(或使用 std::back_inserter
  2. 若输入和输出是同一个容器,可以原地修改(transform(..., input.begin(), ...)
  3. 可与 std::function, lambda 表达式 或 普通函数指针结合使用
  4. 双输入时,第二个序列长度应不少于第一个序列

四、使用 back_inserter 示例(不需要预分配空间):

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

int main() {
    std::vector<int> input = {1, 2, 3};
    std::vector<int> output;

    std::transform(input.begin(), input.end(), std::back_inserter(output),
                   [](int x) { return x * 10; });

    for (int v : output)
        std::cout << v << " ";  // 输出:10 20 30
}

更多推荐