C++模板库STL——map

感觉特别像python里的字典,emmm面向对象果然好用
0、map的定义与访问
代码:

#include <stdio.h>
#include <map>
using namespace std;

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

使用迭代器,map会以键从小到大的顺序自动排序
代码:

#include <stdio.h>
#include <map>
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;
}

1、常用函数
find

#include <stdio.h>
#include <map>
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;
}

erase
mp.erase(it),it为迭代器

#include <stdio.h>
#include <map>
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;
}

mp.erase(key),key为键值

#include <stdio.h>
#include <map>
using namespace std;

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

删除一个区间内的数据

#include <stdio.h>
#include <map>
using namespace std;

int main(){
	map<char,int>mp;
	mp['a'] = 1;
	mp['d'] = 4;
	mp['e'] = 5;
	mp['b'] = 2;
	mp['c'] = 3;
	map<char,int>::iterator it = mp.find('d');
	mp.erase(it,mp.end());//排序后,d及d之后的数据都删除 
	for(map<char,int>::iterator it = mp.begin();it != mp.end();it++ ){
		printf("%c %d\n",it->first,it->second);
	}
	return 0;
}

size用来获得map中映射的对数

#include <stdio.h>
#include <map>
using namespace std;

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

clear()

#include <stdio.h>
#include <map>
using namespace std;

int main(){
	map<char,int>mp;
	mp['a'] = 10;
	mp['b'] = 20;
	mp['c'] = 30;
	mp.clear();//清空map中的所有元素 
	printf("%d\n",mp.size());
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值