STL算法for_each遍历STL容器

#include <iostream>
#include <algorithm>
#include <vector>
#include <map>

using namespace std;

void Func(int i)
{
	cout << i << endl;
}

struct myC
{
	void operator()(int i)
	{
		cout << i << endl;
	}
}myO;

void FunSc(string str)
{
	cout << str.c_str() << endl;
}

struct A
{
	int age;
	string name;
};

void FunA(A param)
{
	cout << param.age << ":" << param.name.c_str() << endl;
}

void FunMap(map<int,string>::reference i)
{
	cout << i.first << ":" << i.second.c_str() << endl;
}

void FunA1(vector<A>::reference param)
{
	cout << param.age << ":" << param.name.c_str() << endl;
}

int main () 
{
	//vector int
	vector<int> vecN;
	vecN.push_back(1);
	vecN.push_back(4);
	vecN.push_back(2);

	for_each(vecN.begin(),vecN.end(),Func); //不能用重载函数
	cout << "使用类中运算符:" <<endl;
	for_each(vecN.begin(),vecN.end(),myO); 

	//vector string
	vector<string> vecStr;
	vecStr.push_back("dai");
	vecStr.push_back("hong");
	vecStr.push_back("hui");

	for_each(vecStr.begin(),vecStr.end(),FunSc);

	//vector 结构体A
	vector<A> vecA;
	A a1;
	a1.age = 10;
	a1.name = "ain";
	vecA.push_back(a1);
	a1.age = 16;
	a1.name = "aain";
	vecA.push_back(a1);
	a1.age = 20;
	a1.name = "20ain";
	vecA.push_back(vector<A>::value_type(a1));

	//for_each(vecA.begin(),vecA.end(),FunA);
	for_each(vecA.begin(),vecA.end(),FunA1);

	//list
	list<string> listStr;
	listStr.push_back("dai");
	listStr.push_back("hong");
	listStr.push_back("hui");

	for_each(listStr.begin(),listStr.end(),FunSc);

	//map
	map<int,string> mapN;
	mapN[1] = "nai";
	mapN[2] = "hai";
	mapN.insert(map<int,string>::value_type(3,"3T"));
	mapN.insert(pair<int,string>(4,"4T"));

	for_each(mapN.begin(),mapN.end(),FunMap);
		
	return(0);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值