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");
}
  •   初始化的賦值的異同
  • 形參和實參賦值的異同


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM