for_each()使用函数对象

C++模板元编程与STL应用实例
本文深入探讨了C++模板元编程的概念及其在标准模板库(STL)中的应用实例,详细介绍了如何使用元编程技术实现高效的数据结构和算法设计。

#include "stdafx.h"
#include <vector>
#include <algorithm>
#include <functional>
#include <iostream>
#include <cstdlib>
#include <iterator>
using namespace std;

class A
{
public:
 A(int i){
 }
 void operator()(int e){
  cout<<e;
 }
};
int mrand()
{
 return rand()%10;
}
int _tmain(int argc, _TCHAR* argv[])
{
 vector<int> ve;
 generate_n(back_inserter(ve),10,mrand);
 for_each(ve.begin(),ve.end(),A(1)); //A(1)就是通过class创建临时对象
 system("pause");
 return 0;
}

`std::for_each` 是 C++ 标准库中的一个算法,定义在头文件 `<algorithm>` 中。它用于对指定范围内的每个元素应用一个函数(或函数对象、lambda 表达式等)。其基本语法如下: ```cpp template<class InputIt, class UnaryFunction> UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f); ``` - `first` 和 `last` 定义了一个范围 `[first, last)`,即从 `first` 开始到 `last` 之前的所有元素。 - `f` 是一个可调用对象函数、lambda、函数对象等),它接受一个参数,参数类型与迭代器指向的元素类型相同。 - `std::for_each` 会依次对范围内的每个元素调用 `f(*it)`。 ### 示例代码: ```cpp #include <iostream> #include <vector> #include <algorithm> // std::for_each int main() { std::vector<int> vec = {1, 2, 3, 4, 5}; // 使用 lambda 表达式打印每个元素 std::for_each(vec.begin(), vec.end(), [](int x) { std::cout << x << " "; }); std::cout << std::endl; // 使用普通函数 void print(int x) { std::cout << x * 2 << " "; } std::for_each(vec.begin(), vec.end(), print); return 0; } ``` ### 输出: ``` 1 2 3 4 5 2 4 6 8 10 ``` ### 注意事项: - `std::for_each` 会遍历范围内的每一个元素,并对其执行指定的操作。 - 如果你希望在操作中修改容器中的元素,可以将参数设为引用类型,例如:`[](int& x) { x *= 2; }`。 - `std::for_each` 返回传入的函数对象(如果函数对象有状态,这可以用来获取其内部状态)。 ### 示例修改容器中的元素: ```cpp std::vector<int> vec = {1, 2, 3, 4, 5}; std::for_each(vec.begin(), vec.end(), [](int& x) { x *= 2; }); // vec 现在是 {2, 4, 6, 8, 10} ``` --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值