map_初探

map是一个很有用的映射工具,底层用红黑树实现,所以也是自动有序的(按照键值key排序)

#include<iostream>
#include<cstdio>
#include<map>
using namespace std;
int main()
{
	//map译为映射,常用的STL容器之一
	//int数组是定义了一个int到int类型的映射,double类型则是定义int到double的映射
	//但数组似乎只能从int映射到其他类型,当我们想要用其他类型进行映射的时候很不方便
	//我们也可以采用hash散列来解决冲突,例如PAT1039中采用的方法
	//但map也给我们提供了解决方案
	//map的功能是可以将任何基本类型(包括STL容器),映射到任何基本类型(同STL)
	
	//map的定义和其他STL容器不同,需要确定映射前类型(键key)和映射后类型(值value)
	//for instance: map<typename1,typename2>mp;
	//如果是字符串映射到整型,只能用string类而不能用char数组 
	
	
	//map有两种访问方式,迭代器访问和下标访问
	//下标访问
	map<char,int>mp;
	mp['c']=20;
	mp['c']=30;//覆盖20 
	printf("visit by rank: %d\n",mp['c']);
	//迭代器访问,it->first是当前映射的键,it->second是当前映射的值
	//因为map内部是用红黑树实现的(同set),在建立映射的过程中自动按key排序 
	map<char,int>mp1;
	mp1['m']=20;
	mp1['r']=30;
	mp1['a']=40;
	for(map<char,int>::iterator it=mp1.begin();it!=mp1.end();it++)
		printf("visit by iterator: %c %d\n",it->first,it->second);
	//find(key)返回键值为key的映射的迭代器,O(logN),N为map中元素数量
	map<char,int> mp2;
	mp2['a']=1; 
	mp2['b']=2;
	mp2['c']=3;
	map<char,int>::iterator it2=mp2.find('b');
	printf("it=mp2.find('b'): %c %d\n",it2->first,it2->second);
	//erase()有两种用法:删除单个元素,删除指定区间的所有元素
	//删除单个元素有两种方法:用mp.erase(it),it是需要删除元素的迭代器,O(1)
	map<char,int>::iterator it=mp2.find('b');
	mp2.erase(it);
	printf("after use erase by it:\n");
	for(map<char,int>::iterator it=mp2.begin();it!=mp2.end();it++)
		printf("%c %d\n",it->first,it->second);
	mp2['b']=2;
	//mp.erase(key),key为欲删除的映射的键,O(logN),N为map内元素个数
	mp2.erase('b');
	printf("restore mp2['b']=2 \nuse erase by key:\n");
	for(map<char,int>::iterator it=mp2.begin();it!=mp2.end();it++) 
		printf("%c %d\n",it->first,it->second);
	//删除区间内的所有元素:mp.erase(first,last),同set和vector一样,[first,last)
	mp2['b']=2;
	printf("restore mp2['b']=2 \nuse erase by erase[]:\n");
	it=mp2.find('b');
	mp2.erase(it,mp2.end());
	for(map<char,int>::iterator it=mp2.begin();it!=mp2.end();it++) 
		printf("%c %d\n",it->first,it->second);
	//size()同样是用来获得map的大小,即映射的对数,O(1)
	mp2['b']=2;
	mp2['c']=3;
	printf("after restore mp2 the size: %d\n",mp2.size());
	//clear()用来清空map中所有元素
	mp2.clear();
	printf("after clear mp2 the size: %d",mp2.size());
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值