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;
}
发布了119 篇原创文章 · 获赞 3 · 访问量 2702

猜你喜欢

转载自blog.csdn.net/weixin_42377217/article/details/104091243
今日推荐