map自用

在这里插入图片描述

#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

  1. node[2] = “value”; 在key值为2处插入value
  2. node2.insert(pair<string, int>(“key”, 26473227)); 在key处插入value数

查找:有map<int, string>::iterator it1; 和 map<string, int>::iterator it2;

  1. it1 = node1.find(2) 和 it2 = node2.find(“key”)
    于是有 it-1->first 为 2, it2->second 为 2647322
  2. string a = node[2]; a 为 2647322

看某个key是否已经使用过

  1. node2.count(“key”)
    等于0就是没存在 1就是存在了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值