欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 新闻 > 国际 > c++中std::transform详解和应用代码示例

c++中std::transform详解和应用代码示例

2025/6/20 14:52:51 来源:https://blog.csdn.net/qq_36812406/article/details/148765605  浏览:    关键词:c++中std::transform详解和应用代码示例

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
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词