std::for_each是C++标准库

std::for_each基本语法
std::for_each的函数原型如下:
template<class InputIt, class UnaryFunction> UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f);
参数说明:
- first:遍历范围的起始迭代器,指向第一个要处理的元素
- last:遍历范围的结束迭代器,指向最后一个要处理元素的下一个位置,属于左闭右开区间
- f:要执行的回调函数,可以是普通函数、函数对象、lambda表达式,接收单个参数,参数类型为容器元素的类型
返回值:返回传入的回调函数f,方便后续链式调用。
不同场景下的使用方式
1. 配合普通函数使用
定义普通函数作为回调,处理容器中的每个元素:
#include <algorithm>
#include <vector>
#include <iostream>
// 普通函数,打印int元素
void print_int(int num) {
std::cout << num << " ";
}
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
// 遍历vector,对每个元素执行print_int
std::for_each(vec.begin(), vec.end(), print_int);
// 输出结果:1 2 3 4 5
return 0;
}
2. 配合函数对象使用
函数对象即重载了operator()的类实例,可以携带状态:
#include <algorithm>
#include <vector>
#include <iostream>
// 函数对象,累计元素总和
class SumCalculator {
public:
SumCalculator() : total(0) {}
void operator()(int num) {
total += num;
}
int get_total() const {
return total;
}
private:
int total;
};
int main() {
std::vector<int> vec = {1, 2, 3, 4, 5};
SumCalculator calculator;
// 遍历并累计总和
SumCalculator result = std::for_each(vec.begin(), vec.end(), calculator);
std::cout << "总和:" << result.get_total() << std::endl;
// 输出结果:总和:15
return 0;
}
3. 配合lambda表达式使用
lambda表达式是日常开发中最常用的方式,代码更简洁:
#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
int main() {
std::vector<std::string> str_vec = {"hello", "world", "cpp"};
// lambda表达式作为回调,拼接字符串
std::string combined;
std::for_each(str_vec.begin(), str_vec.end(), [&combined](const std::string& s) {
combined += s;
combined += " ";
});
std::cout << "拼接结果:" << combined << std::endl;
// 输出结果:拼接结果:hello world cpp
return 0;
}
遍历关联容器的注意事项
遍历map、set等关联容器时,元素类型是键值对,需要注意回调参数的类型:
#include <algorithm>
#include <map>
#include <iostream>
int main() {
std::map<int, std::string> id_name_map = {
{1, "张三"},
{2, "李四"},
{3, "王五"}
};
// 遍历map,回调参数类型为std::pair<const int, std::string>
std::for_each(id_name_map.begin(), id_name_map.end(), [](const std::pair<const int, std::string>& item) {
std::cout << "id:" << item.first << ",姓名:" << item.second << std::endl;
});
return 0;
}
适用场景与注意事项
std::for_each适合需要对容器内所有元素执行相同操作的场景,相比传统for循环,语义更明确,减少迭代器操作出错的概率。需要注意遍历区间是左闭右开,不要传入错误的迭代器范围,同时回调函数如果不需要修改元素,建议加上const修饰,避免意外修改元素值。
std::for_eachC++容器遍历算法修改时间:2026-07-18 07:57:20