map用法小结

定义

map为映射
可以将任何基本类型(包括STL容器)映射到任何基本类型(包括STL容器),也可以建立string到int的类型

map<typename1,typename2> mp;

map容器内元素的访问

通过下标访问

map中键值是唯一的
map以键从小到大自动排序
it->first来访问键,it->second来访问值

通过迭代器访问

常用函数

find()

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

#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<char,int> mp;
int main(){
	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);
}
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<pair<int,int>,int> mp;
int main(){
	for(int i=1;i<=10;i++){
		mp[make_pair(i,i)]=i;
	}
	map<pair<int,int>,int>::iterator it=mp.find(make_pair(5,5));
	cout<<it->first.first<<" "<<it->first.second<<" "<<it->second<<endl;
}
#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
struct node{
	int x,y;
	bool operator<(const node&a) const{
		if(x!=a.x)
		return x>a.x;
		else return y>a.y;
	}
};
map<node,int> mp;
node p;
int main(){
	for(int i=1;i<=10;i++){
		p.x=i*i;p.y=i*i*i;
		mp[p]=i;
	}
	map<node,int>::iterator it;
	for(it=mp.begin();it!=mp.end();it++){
		cout<<it->first.x<<" "<<it->first.y<<" "<<it->second<<endl;
	}
	p.x=25;p.y=125;
	it=mp.find(p);
	cout<<it->first.x<<" "<<it->first.y<<" "<<it->second<<endl;
}

erase()

erase()删除单个元素,删除一个区间内的所有元素
删除单个元素有两种方法:
(1)mp.erase(it),it为迭代器,O(1)
(2)mp.erase(key),key为键,O(logN),N为map内元素的个数

#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<char,int> mp;
int main(){
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	mp['d']=4;
	map<char,int>::iterator it;
	it=mp.find('c');
	mp.erase(it);
	mp.erase('d');
	for(it=mp.begin();it!=mp.end();it++)
	cout<<it->first<<" "<<it->second<<endl;
}

删除一个区间内所有元素
mp.erase(first,last).时间复杂度O(last-first).

#include<cstdio>
#include<iostream>
#include<map>
using namespace std;
map<char,int> mp;
int main(){
	mp['a']=1;
	mp['b']=2;
	mp['c']=3;
	mp['d']=4;
	map<char,int>::iterator it;
	it=mp.find('b');
	mp.erase(it,mp.end());
	for(it=mp.begin();it!=mp.end();it++)
	cout<<it->first<<" "<<it->second<<endl;
}

size()

获得map中映射的对数,O(1)

clear()

清空所有元素,复杂度O(N),N为map中元素的个数

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值