STL:map

1. map是标准的关联式容器,它提供了快速检索能力,在一个map中key值是唯一的。map提供了双向迭代器:iterator和reverse_iterator(rbegin(),rend());

2. map要求能对key进行'<'操作,即保持key值递增有序,如果不需要保证元素有序,可以采用hash_map;

int main()
{
	map<pair<int ,int>, int> mapContainer;
	mapContainer.insert(<span style="color:#ff0000;">make_pair</span>(pair<int,int>(1,2), 5));
	mapContainer.insert(make_pair(pair<int,int>(0,4), 6));

	map<pair<int ,int>, int>::iterator iter = mapContainer.begin();
	cout<<(iter->first).first<<" "<<(iter->first).second<<endl;    //这儿输出的是0和4,这里可以看出,是按照键里面的pair键来排序的。

	return 0;
}

3. map的插入方法:insert()和[ ]。

insert方法的返回值是pair<iterator, bool>,如果键重复则插入失败,bool返回false,若成功iterator指向插入的map,bool返回true;与[ ]插入失败的区别是:它不会覆盖以前的值,而[ ]会。

map.insert(make_pair(x,y));

4.map的查找:count和find。

count是寻找关键字是否在map中出现,出现则返回1,否则返回0;缺点是:不能定位该关键字在元素中的作用;

find不但能寻找关键字是否存在,还能定位其位置;返回一个迭代器,如果未找到,则返回end函数迭代器;

int main()
{
	map<int, int> mapVec;
	mapVec[1] = 4;
	mapVec[4] = 67;
	mapVec.insert(make_pair(8,6));
	
	int flag = mapVec.count(4);

	map<int, int>::iterator iter = mapVec.find(4);
	cout<<iter->first<<" "<<iter->second<<endl;

	iter = mapVec.find(9);
	if(iter == mapVec.end())
		cout<<"Can't find it "<<endl;

	return 0;
}

5.map的排序

map默认有less函数,但是当有自定义类作为键的时候,需要自己重载‘<’符号;

struct Student
{
	int id;
	double score;
	Student(int i=0, double sc=0):id(i),score(sc){}

	//error C2678: binary '<' : no operator defined which takes a left-hand operand of type 'const struct Student' 
	bool operator < (const Student &stu) const   //记住,最后一个const必须加,不然出现上述错误。
	{
		return score < stu.score; 
	}
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值