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

本文通过C++代码示例介绍了如何使用不同方法遍历vector容器中的元素,包括普通函数、函数对象以及成员函数,并对比了形参与实参在赋值过程中的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#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");
}
  •   初始化的赋值的异同
  • 形参和实参赋值的异同

转载于:https://www.cnblogs.com/xiaochige/p/6959129.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值