map的用法------------------C++

map–映射 常用的STL容器

#include
using namespace std;

//map定义
map<typename1,typename2>mp;//映射前类型(键key),映射后类型(值value)

//字符串映射整数数组
map<string,int>mp;

//将set容器映射到一个字符串
map<set<int>,string>mp;
map容器内元素的访问

1、通过下标访问
例如:
mapmp;
mp[‘c’]=20;

#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['c']=20;
	mp['c']=30;//20被覆盖 
	printf("%d\n",mp['c']);//输出30 
	return 0}

2、通过迭代器访问

//通过迭代器定义与其他STL容器迭代器定义方式相同
map<typename1,typename2>::iterator it; 

通过it同时访问键和值
map可以用it->first访问键,用it->second访问值

#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['m']=20;
	mp['r']=30;
	mp['a']=40;
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
     
		printf("%c %d\n",it->first,it->second);
	}
	return 0;
}

注:map会以键从小到大的顺序自动排序

map常用函数实例

1、find()

//find(key)返回键为key的映射迭代器,时间复杂度为O(logN),N为map中映射的个数

#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	map<char,int>::iterator
	 it=mp.find('b');
	printf("%c %d\n",it->first,it->second);
	return 0;
}

2、erase()

两种用法:删除单个元素、删除一个区间内的左右元素

1)、删除单个元素
map.erase(it),it为需要删除元素的迭代器,时间复杂度为O(1)

#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	map<char,int>::iterator it=mp.find('b');
	mp.erase(it);
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
     
		printf("%c %d\n",it->first,it->second);
	}
	return 0;
}

map.erase(key),key为欲删除映射的键,时间复杂度 为O(logN),N为map内元素的个数

#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	mp.erase('b');//删除键为b的映射,即b 2 
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
     
		printf("%c %d\n",it->first,it->second);
	}
	return 0;
}

2)、删除一个区间内所有元素
mp.erase(first,last),first为需要删除的区间起始迭代器,last为需要删除的区间的末尾迭代器的下一个地址,即删除左闭右开[first,last),时间复杂度为O(last-first)

#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	map<char,int>::iterator it=mp.find('b');
	mp.erase(it,mp.end()); //删除it之后的左右映射,即b 2,c 3 
	for(map<char,int>::iterator it=mp.begin();it!=mp.end();it++){
     
		printf("%c %d\n",it->first,it->second);
	}
	return 0;
}

3、size()

size()用来获得map中映射的对数,时间复杂度O(1)
#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['a']=10;
	mp['b']=20;
	mp['c']=30;
	printf("%d\n",mp.size());//3对映射 
	return 0;
}

4、clear()

clear()用来清空map中所有元素,复杂度O(N),N为map中元素的个数
#include
#include
using namespace std;

int main(){
     
	map<char,int>mp;
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	mp.clear(); //清空map 
	printf("%d\n",mp.size());
	return 0;
}

map常见用途

1、需要建立字符(或字符串)与整数之间映射的题目,使用map可以减少代码量

2、判断大的整数或者其他类型数据是否存在的题目,可以把map当bool数组用

3、字符串和字符串的映射也可能遇到

注:

map键和值是唯一的,如果一个键需要多个值,只能用multimap

你可能感兴趣的:(算法笔记,算法,数据结构)