stl中的for_each() 函数的注意事项

#include<iostream>
using namespace std;
#include"vector"
#include"algorithm"
//
void PrintV(vector <int > &temp)
{
	for (vector<int>::iterator it = temp.begin(); it != temp.end(); it++)
	{
		cout << *it << " ";
	}
	cout << endl;
}
void showV(int &n)
{
	cout << n << " ";
}
class C_showV
{
public:
	void operator() (int &n)
	{
		cout << n << " ";
	}
protected:
private:

};
class C_showV2
{
public:
	C_showV2()
	{
		this->num = 0;
	}
	void operator() (int &n)
	{
		num++;
		cout << n << " ";
	}
	void PrintN()
	{
		cout << num << endl;
	}
protected:
private:
	int num;
};
int main()
{
	vector <int> v1;
	v1.push_back(1);
	v1.push_back(6);
	v1.push_back(3);
	v1.push_back(18);
	cout << "PrintV(v1) +++++> ";
	PrintV(v1);
	cout << endl;
	cout << "运用回调函数入口实现:for_each(v1.begin(), v1.end(),showV )+++++> ";
	for_each(v1.begin(), v1.end(),showV );
	cout << endl;
	cout << "运用函数对象入口实现:for_each(v1.begin(), v1.end(),C_showV())+++++> ";
	for_each(v1.begin(), v1.end(), C_showV());
	cout << "\n我是漂亮的分割线,接下来针对于函数对象的几种情况:\n";

	C_showV2 tem1 = for_each(v1.begin(), v1.end(), C_showV2());
	cout << endl;
	tem1.PrintN();//4

	C_showV2 tem2;
	C_showV2 tem11 = for_each(v1.begin(), v1.end(), tem2); // 初始化
	cout << endl;
	tem11.PrintN(); //4
	tem2.PrintN();// 0 tem2和tem1的值不相同的主要原因是实参和形参,在加上for_each的定义是元素 不是引用。


	tem11 = for_each(v1.begin(), v1.end(), tem2);//赋值
	cout << endl;
	tem11.PrintN();//4
	system("pause");
}
  •   初始化的赋值的异同
  • 形参和实参赋值的异同
posted @ 2017-06-07 21:24  小陈同学啦  阅读(1593)  评论(0编辑  收藏  举报