更加准确的表述:传送门
/*****************************/
用法类似于哈希表
一维
小结:
- 头文件#include < map >
- 定义:map<int,bool>mp;
- 定义:map<int,int>mp;
使用:
清除容器数据:mp.clear()
将出现的数字进行标记:map[num]=true;
将出现的数字次数进行累加:map[num]++;
查找num是否出现:if ( mp[num]==true )
输出num出现过几次:printf("%d",mp[num]);
样例代码:
#include<stdio.h>
#include<map>
using namespace std;
int main()
{
/*
map<int,bool>mp;
mp.clear();
for(int i=0;i<=10;i++)
if(i%2==1)
mp[i]=true;
else
mp[i]=false;
for(int i=0;i<=10;i++)
if(mp[i]==true)
printf("%d ",i)
*/
map<int,int>mp;
mp.clear();
mp[1]++;
mp[1]++;
mp[1]++;
mp[2]++;
mp[2]++;
mp[3]++;
for(int i=0;i<5;i++)
if(mp[i]!=0)
printf("%d出现过%d次\n",i,mp[i]);
return 0;
}
二维
小结:
- 头文件#include < map >
- 定义:map<int,map<int,int>>mp;
使用:
清除容器数据:mp.clear()
在(x,y)的位置赋step值:mp[x][y]=step
查找(x,y)的位置上是否有值:if ( mp[x][y]==0 )
练习题链接1
练习题链接2
AC代码:
#include<stdio.h>
#include<map>
using namespace std;
typedef long long ll;
const int MAX=2e+5;
char str[MAX];
map<int,map<int,int>>mp;
int main()
{
int T;
while(scanf("%d",&T)!=EOF)
{
while(T--)
{
mp.clear();
int n;
scanf("%d",&n);
scanf("%s",str+1);
int l,r,x=0,y=0;
//题意:删除可能最短的非空子串来优化机器人的路径
int mi=n+2;
for(int i=1; i<=n; i++)
{
if(str[i]=='L') x--;
else if(str[i]=='R') x++;
else if(str[i]=='U') y++;
else if(str[i]=='D') y--;
if(x==0&&y==0&&i<mi)
mi=i,l=0,r=i;
if(mp[x][y]!=0&&(i-mp[x][y])<mi)
mi=i-mp[x][y],l=mp[x][y],r=i;
mp[x][y]=i;
}
if(mi==n+2)
printf("-1\n");
else
printf("%d %d\n",l+1,r);
}
}
return 0;
}
其它:
成员方法 | 功能 |
---|---|
begin() | 返回指向map头部的迭代器 |
end() | 返回指向map末尾的迭代器 |
clear() | 删除所有元素 |
count() | 返回指定元素出现的次数 |
empty() | 如果map为空则返回true |
insert() | 插入元素 |
erase() | 删除一个元素 |
find() | 查找一个元素 |
swap() | 交换两个map |
size() | 返回map中元素的个数 |
upper_bound() | 返回键值大于给定元素的第一个位置 |