C++STL——关联式容器(map)超详细!!!

map 是有序键值对容器,它的元素的键是唯一的。它提供一对一的hash。

若想了解hash戳戳这里:字符串哈希hash_Rudy1124的博客-CSDN博客

你可能需要存储一些键值对,例如存储学生姓名对应的分数:小明 70 小黄 81 小红97。但是由于数组下标只能为非负整数,所以无法用姓名作为下标来存储,这个时候最简单的办法就是使用 STL 中的 map 了!

map的用法:

头文件:

#include<map>

声明:

map 重载了 operator[],可以用任意定义了 operator < 的类型作为下标(在 map 中叫做 key,也就是索引):

map<key,类型> 名称;

例如:

map<string,int> mp;

map 中不会存在键相同的元素,multimap 中允许多个元素拥有同一键。multimap 的使用方法与 map 的使用方法基本相同。

PS:正是因为 multimap 允许多个元素拥有同一键的特点,multimap 并没有提供给出键访问其对应值的方法。

插入与输出:

  • 可以直接通过下标访问来进行查询或插入操作。例如 mp["Alan"]=100
  • 通过向 map 中插入一个类型为 pair<Key, T> 的值可以达到插入元素的目的,例如 mp.insert(pair<string,int>("Alan",100));
  • erase(key) 函数会删除键为 key 的 所有 元素。返回值为删除元素的数量。
  • erase(pos): 删除迭代器为 pos 的元素,要求迭代器必须合法。
  • erase(first,last): 删除迭代器在 [first,last) 范围内的所有元素。
  • clear() 函数会清空整个容器。

 举个栗子:

#include<bits/stdc++.h>

using namespace std;

int main(){
	map<char,string> mp;
	mp['h']="hello";
	mp['b']="bye bye";
	mp['s']="see you next time";
	cout<<"mp['h']="<<mp['h']<<endl;
	cout<<"mp['b']="<<mp['b']<<endl;
	cout<<"mp['s']="<<mp['s']<<endl;
	/*
	mp['h']=hello
	mp['b']=bye bye
	mp['s']=see you next time
	*/
	return 0;
}

当然怎么写也是可以的:

#include<bits/stdc++.h>

using namespace std;

int main(){
	map<char,string> mp;
	mp.insert(pair<char,string>('h',"hello"));
	mp.insert(pair<char,string>('b',"bye bye"));
	mp.insert(pair<char,string>('s',"see you next time"));
	cout<<"mp['h']="<<mp['h']<<endl;
	cout<<"mp['b']="<<mp['b']<<endl;
	cout<<"mp['s']="<<mp['s']<<endl;
	/*
	mp['h']=hello
	mp['b']=bye bye
	mp['s']=see you next time
	*/
	return 0;
}

pair不懂的去查哦!!!

再举个栗子(啊,我爱举例子!):

#include<bits/stdc++.h>

using namespace std;

int main(){
	map<char,string> mp;
	mp.insert(pair<char,string>('h',"hello"));
	mp.insert(pair<char,string>('b',"bye bye"));
	mp.insert(pair<char,string>('s',"see you next time"));
	cout<<"mp['h']="<<mp['h']<<endl;
	cout<<"mp['b']="<<mp['b']<<endl;
	cout<<"mp['s']="<<mp['s']<<endl;
	cout<<mp.erase('s')<<endl;
	cout<<"mp['s']="<<mp['s']<<endl;//会发现什么也没有输出,因为被删除了
	mp.clear();
	if(mp.empty()){
		cout<<"mp is empty!!!";
	}
	else cout<<"mp is not empty!!!";
	/*
	mp['h']=hello
	mp['b']=bye bye
	mp['s']=see you next time
	1
	mp['s']=
	mp is empty!!!
	*/
	return 0;
}

再看一个:

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

int main() {
    map<int, int> mymap;
    for (int i = 0; i < 20; i++) {
        mymap.insert(make_pair(i, i));
    }
    mymap.erase(0);          	 // (1)删除key为0的元素
    mymap.erase(mymap.begin());  // (2)删除迭代器指向的位置元素
    map<int, int>::iterator it;
    for (it = mymap.begin(); it != mymap.end(); it++) {
        cout << it->first << "==>" << it->second << endl;
    }
    return 0;
}

遍历容器:

不懂看这:C++STL容器入门1(迭代器Iterator)!_Rudy1124的博客-CSDN博客

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值