题目
编写程序,演示现代 C++ 中函数式编程的两大支柱算法:一元与二元映射 std::transform(将集合批量变换产生新集合,如将所有数值平方或两个向量逐元素点相加)与数值折叠规约 std::accumulate(在 <numeric> 中,实现元素累加求和、累乘积以及自定义聚合逻辑,如拼接带分隔符的字符串)。
输入格式:无需外部输入。
输出格式:输出向量映射计算、逐元素相加与字符串聚合规约的执行结果。
数据范围与约定:函数式泛型算法、折叠运算与内存开销优化。
思路与算法
1. transform 的就地与异地写回std::transform 支持输入迭代器与输出迭代器完全相同(就地修改 vec.begin()),也支持写入新的目标容器(需保证目标容器已有充足容量或配合 std::back_inserter)。
2. accumulate 的初值类型推导陷阱std::accumulate(begin, end, 0) 的初值若传入整数 0,即使原数组是 double,中间累加过程也会被隐式截断为 int!若求浮点总和必须显式传入 0.0。
3. 自定义折叠仿函数accumulate 第四个参数接收二元谓词 [](AccType acc, const ElemType& item),可用于实现任意高阶统计(如多字段求总和、拼接 CSV 报表)。
完整程序
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
#include <string>
int main() {
std::vector<int> a = {1, 2, 3, 4, 5};
std::vector<int> b = {10, 20, 30, 40, 50};
// 1. 一元 transform: 将 a 中所有元素计算平方
std::vector<int> squared(a.size());
std::transform(a.begin(), a.end(), squared.begin(), [](int x) {
return x * x;
});
std::cout << "向量 a 平方映射: ";
for (int x : squared) std::cout << x << " ";
std::cout << "\n";
// 2. 二元 transform: a 与 b 对应元素逐位相加
std::vector<int> sumVec(a.size());
std::transform(a.begin(), a.end(), b.begin(), sumVec.begin(), [](int x, int y) {
return x + y;
});
std::cout << "向量 a + b 元素对位相加: ";
for (int x : sumVec) std::cout << x << " ";
std::cout << "\n\n";
// 3. std::accumulate 整数累加与累乘
long long totalSum = std::accumulate(a.begin(), a.end(), 0LL);
long long totalProduct = std::accumulate(a.begin(), a.end(), 1LL, [](long long acc, int x) {
return acc * x;
});
std::cout << "a 元素累加和: " << totalSum << ", 元素累乘积: " << totalProduct << "\n";
// 4. accumulate 自定义折叠:将字符串列表拼接为逗号分隔的单串
std::vector<std::string> words = {"Modern", "C++", "Functional", "Programming"};
std::string joined = std::accumulate(
std::next(words.begin()), words.end(), words[0],
[](std::string acc, const std::string& w) {
return acc + ", " + w;
}
);
std::cout << "accumulate 字符串折叠拼接: \"" << joined << "\"\n";
return 0;
}运行示例
输出:
向量 a 平方映射: 1 4 9 16 25
向量 a + b 元素对位相加: 11 22 33 44 55
a 元素累加和: 15, 元素累乘积: 120
accumulate 字符串折叠拼接: "Modern, C++, Functional, Programming"