for_each一探

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014303647/article/details/83744951

最近在看到for_each的时候我就挺好奇的,这个东西到底怎么实现的,然后我就配合仿函数实现了一个小例子。

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<stack>
#include<map>
#include<memory>
#include<cstdio>
#include<hash_map>
#include<string>
#include<algorithm>
#include<functional>
using namespace std;

const int maxn = 100 + 10;

bool cmp(const int a, const int b)
{
	return a > b;
}

void add(int i,const char* str)
{
	cout << str << " " << i << endl;
}

struct play
{
	string add_string;
	play(string str) :add_string(str)
	{
		cout << "调用了play()构造函数" << endl;
	}
	play(const play& rhs)
	{
		cout << "调用了play()的复制构造函数" << endl;
		add_string = rhs.add_string;
	}
	void operator()(int i)
	{
		cout << add_string << " " << i << endl;
	}
	~play()
	{
		cout << "调用了play()析构函数" << endl;
	}
};





int main()
{
	initializer_list<int>  lst = { 5, 4, 10, 8, 7, 6,24,56};
	vector<int> vec(lst);
	//greater<int>是个仿函数的临时对象
	for_each(vec.begin(), vec.end(), play("data member: "));
	cout << endl;
	return 0;
}

最后的运行结果是

在这里插入图片描述那是为什么会调用1次构造函数和两次复制构造函数呢

调用一次构造函数我们能够理解,因为有paly(“data member: ”),为什么会调用2次复制构造函数呢?我们看下源码就明白了。

template<class _InIt,
	class _Fn1> inline
	_Fn1 for_each(_InIt _First, _InIt _Last, _Fn1 _Func)
	{	// perform function for each element
	_DEBUG_RANGE(_First, _Last);
	_DEBUG_POINTER(_Func);
	_For_each(_Unchecked(_First), _Unchecked(_Last), _Func);

	return (_STD move(_Func));
	}

因为for_each的第三个参数是个可调用对象,所以传递过去的时候会调用复制构造函数,最后有个return 又会调用一个复制构造函数,所以最后调用了1次构造函数,2次复制构造函数。

猜你喜欢

转载自blog.csdn.net/u014303647/article/details/83744951