STL map的基本用法

map容器

  • **<键,值>**对
    在这里插入图片描述

  • 键值不允许重复。

  • 如果map中没有键值,而直接插入,则操作是允许的;另外如果直接使用“++”运算符,则从0开始直接计数。并把这个<键,值>对插入到map中。

常用函数和操作
1.map的创建、插入和遍历

#include<map>
#include<iostream>
#include<string>
using namespace std;

int main()
{
	map<string, float> a;
	a["hehe"] = 12.5;
	a["xixi"] = 89.6;
	map<string, float>::iterator it;
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
	a["hehe"] = 45.2;
	cout<<"修改后的hehe的值:"<<a["hehe"]<<endl;	
}

上面的代码的运行截图

(*it).first     表示键,注意键不可以用这种方法修改,如:
(*it).first = "eee",是错误的操作。
(*it).second    表示对应的值

2.查找键和删除键
可以使用clear()清空map

map<int, int> a;
a.clear();

也可以使用erase()删除。括号中可以直接写相应的键值,也可以写iterator的位置。

a.erase("hehe");//直接使用键,删除“hehe”;
a.erase(++a.begin());//删除“xixi”

使用**find()**函数可以搜索某个键。搜索到了的话返回迭代器的位置,搜索不到返回end()位置。

#include<map>
#include<iostream>
#include<string>
using namespace std;

int main()
{
	map<string, float> a;
	a["hehe"] = 12.5;
	a["xixi"] = 89.6;
	map<string, float>::iterator it;
	it = a.find("xixi");
	a.erase(it); 
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
}

另外,把元素插入到map中时,自动按照键值从小到大排序。可以自己设置比较函数,比较函数的写法类似于sort()中的写法。

//未使用自定义比较函数时
#include<iostream>
#include<map>
using namespace std;
bool comp(int a, int b){
}
int main()
{
	map<int, char> a;
	a[10] = 'a';
	a[5] = 'b';
	a[25] = 'c';
	a[15] = 'd';
	map<int, char>::iterator it;
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
}

在这里插入图片描述

#include<iostream>
#include<map>
using namespace std;
struct mycomp
{
	bool operator() (const int &a, const int &b)
		return a > b;
};
int main()
{
	map<int, char, mycomp> a;
	a[10] = 'a';
	a[5] = 'b';
	a[25] = 'c';
	a[15] = 'd';
	map<int, char, mycomp>::iterator it;
	for(it = a.begin(); it != a.end(); it++)
		cout<<(*it).first<<' '<<(*it).second<<endl;
}

对于结构体,需要重载。。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值