for_each详解

for_each如何调用function obj的过程

#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;
}

输出

//执行for_each后,返回了一个play() function对象,所以会是这样。
new a Play
1
3
4
5
new a copy Play
dispose a Play
dispose a Play
See something
全部评论

相关推荐

点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务