C++中std::for_each的使用
作者:点云SLAM
std::for_each是C++标准库中的一个算法,用于遍历容器并对每个元素执行指定的操作,本文就来介绍一下C++中std::for_each的使用,感兴趣的可以了解一下
std::for_each的使用
std::for_each 是 C++ 标准库中的一个算法,用于遍历容器并对每个元素执行指定的操作。适用于 std::vector、std::list、std::array 等标准容器。
1. 语法
#include <algorithm> template<class InputIt, class UnaryFunction> UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f);
first:起始迭代器(包含)。last:结束迭代器(不包含)。f:对元素执行的函数对象,接受单个参数。
返回值:
返回 f,即传入的函数对象(可用于累积状态)。
2. 基本用法
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用 std::for_each 遍历并打印元素
std::for_each(vec.begin(), vec.end(), [](int x) {
std::cout << x << " ";
});
return 0;
}
输出
1 2 3 4 5
3. 使用普通函数
#include <iostream>
#include <vector>
#include <algorithm>
// 普通函数
void printElement(int x) {
std::cout << x << " ";
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::for_each(vec.begin(), vec.end(), printElement);
return 0;
}
4. 使用 std::for_each 计算累积和
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
int sum = 0;
std::for_each(vec.begin(), vec.end(), [&sum](int x) {
sum += x;
});
std::cout << "Sum: " << sum << std::endl;
return 0;
}
输出
Sum: 15
这里使用了 Lambda 捕获 [&sum] 来累加元素值。
5. 使用 std::for_each 修改元素
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 使用 std::for_each 修改元素
std::for_each(vec.begin(), vec.end(), [](int &x) {
x *= 2;
});
// 输出修改后的值
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
输出
2 4 6 8 10
注意:需要传递 int &x 才能修改原数据。
6. 与 range-based for 循环对比
使用 for_each 适用于需要函数对象(如 Lambda 或 functor),但 C++11 之后的 范围 for 循环 更简洁:
for (int &x : vec) {
x *= 2;
}
相比 std::for_each,范围 for 在可读性上更好。
7. for_each 与函数对象
可以使用自定义仿函数:
#include <iostream>
#include <vector>
#include <algorithm>
struct Multiply {
void operator()(int &x) const {
x *= 3;
}
};
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
std::for_each(vec.begin(), vec.end(), Multiply());
for (int num : vec) {
std::cout << num << " ";
}
return 0;
}
输出
3 6 9 12 15
仿函数 适用于复杂操作或需要在多个地方复用时。
8. 总结
| 方法 | 可读性 | 适用场景 |
|---|---|---|
| std::for_each | 适中 | 需要 Lambda、仿函数或函数指针 |
| range-based for | 高 | 适用于大多数遍历任务 |
| 普通 for 循环 | 低 | 需要索引访问元素 |
当代码需要传递回调(如 std::transform 或 std::accumulate 结合使用)时,std::for_each 更合适,否则推荐 范围 for 语法。
到此这篇关于C++中std::for_each的使用的文章就介绍到这了,更多相关C++ std::for_each内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
