#include<bits/stdc++.h>
#include<map>//也包含在万能头文件里
//map內部的实现自建一颗红黑树,这颗树具有对数据自动排序的功能。
using namespace std;
int main()
{
map<int, int> node;
//可以把 pair看为存在 map中的一个结构体,它里面有 key和 value
node.insert(pair<int, int>(1, 1));//这种方法赋值相同的 key无法赋值 具有唯一性
node[10] = 10;//这样赋值如果key值相同可以覆盖
//auto是根据后面的数据来推断它是什么类型 自动赋予相应的类型
for(auto it=node.begin(); it!=node.end(); it++)
cout << it->first << " " << it->second << endl;
printf("\n");
//map<string,int>::iterator it; 定义一个名为 it 的 map迭代器
map<int, int>::iterator a = node.find(10);//查找 key为10的 pair型
cout << a->first << " " << a->second;
return 0;
}
例题:寄包柜
https://www.luogu.com.cn/problem/P3613
这一用到了二维的map
#include<bits/stdc++.h>
using namespace std;
int main()
{
//注意下面是map<int, int> +空格 + > (洛谷似乎说这样才符合规范)
map< long, map<int, int> > node;
int n, q;
cin >> n >> q;//柜子数 操作次数
for(int t=1; t<=q; t++)
{
int num;
cin >> num;
if(num == 1){
int i, j, k;
cin >> i >> j >> k;
node[i][j] = k;
}
else{
int i, j;
cin >> i >> j;
cout << node[i][j] << endl;
}
}
return 0;
}
对map的理解参考:
https://blog.csdn.net/sevenjoin/article/details/81943864
map与set的区别:
https://www.cnblogs.com/xietianjiao/p/12875939.html
快速回忆(自用):
插入:有 map<int, string>node1 和 map< string, int>node2
- node[2] = “value”; 在key值为2处插入value
- node2.insert(pair<string, int>(“key”, 26473227)); 在key处插入value数
查找:有map<int, string>::iterator it1; 和 map<string, int>::iterator it2;
- it1 = node1.find(2) 和 it2 = node2.find(“key”)
于是有 it-1->first 为 2, it2->second 为 2647322- string a = node[2]; a 为 2647322
看某个key是否已经使用过
- node2.count(“key”)
等于0就是没存在 1就是存在了