c++ for_each( )学习
for_each()事实上是個 function template,其实质如下 [effective STL item 41]
template<typename InputIterator, typename Function>
Function for_each(InputIterator beg, InputIterator end, Function f) {
while(beg != end)
f(*beg++);
}
能看懂吧!!!
Object Oriented 与for_each 搭配
1、不传入参数,使用function object
#include<iostream> #include<vector> #include<algorithm> #include<typeinfo> using namespace std; struct Play { void operator () (int i) { cout<<i<<endl; } }; int main() { int a[] = { 1, 3, 4, 5}; vector<int> vc(a, a+sizeof(a)/sizeof(int)); for_each(vc.begin(), vc.end(), Play()); }
#include<iostream> #include<vector> #include<algorithm> #include<typeinfo> using namespace std; struct Play { Play() { cout<<"new a Play"<<endl; } Play(const Play&) { cout<<"new a copy Play"<<endl; } void operator () (int i) { cout<<i<<endl; } ~Play() { cout<<"dispose a Play"<<endl; } }; int main() { int a[] = { 1, 3, 4, 5}; vector<int> vc(a, a+sizeof(a)/sizeof(int)); for_each(vc.begin(), vc.end(), Play()); cout<<"See something"<<endl; }
结果如下:
new a Play
1
3
4
5
new a copy Play
dispose a Play
dispose a Play
See something
可以看到这个过程有两个Play对象生成,但是,用于输出元素的却是第一个对象(重载() 操作符),为什么?
这时候回去看for_each的源码,就会发现,它的返回值是function,以我的猜测,应该是这样的。
Play() 生成一个临时的匿名的Play对象,传入for_each 函数里,然后执行完for_each 函数后,return一个function时,Play用复制构造函数生成一个Play对象,然后两个Play对象的生命周期都结束,于是依次销毁。
2、传入参数
可以通过构造函数的技巧传入参数
#include<iostream> #include<vector> #include<algorithm> #include<typeinfo> using namespace std; struct Play { const char* str; Play(const char* s):str(s) {} void operator () (int i) { cout<<str<<i<<endl; } }; int main() { int a[] = { 1, 3, 4, 5}; vector<int> vc(a, a+sizeof(a)/sizeof(int)); for_each(vc.begin(), vc.end(), Play("Element:")); //其实 还是关键看 Play函数如何实现的! }
结果:
Element:1
Element:3
Element:4
Element:5
Member function 与 for_each 搭配
1、不传入参数
通过mem_fun_ref() 这个funtion adapater 将 member funtion 转成 function object。
先到这里吧 下次 继续 !!!!
posted on 2018-07-26 17:16 zhangkele 阅读(40304) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧