#include<map>
map容器是一个键值对(key-value)映射,key和value可以是任意的类型
通常用于类型之间的映射问题
声明方法:map<key_type,value_type> name;
ex:
map<long,bool>vis;
map<string,int>hash;
map<pair<int,int>,vector<int>> test;
内置函数;
size / empty / clear //元素个数、判空、清空
begin / end //首尾迭代器
insert / erase //插入和删除
insert的参数是pair<key_type,value_type>
erase的参数是迭代器
find
h.find(x)是在变量名为h的map中查找key值为x的二元组,返回指向二元组的迭代器;若没找到,返回h.end()
#include<map>
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
map<int,int>h;
h.insert(make_pair(1,2));
h.insert(make_pair(3,4));
map<int,int>::iterator it;
it=h.find(3);
cout<<"map容器h中3对应的的值为:";
cout<<it->second<<endl<<endl;
cout<<"遍历map容器h:"<<endl;
h[100]=999;
for(it=h.begin();it!=h.end();it++)
cout<<it->first<<' '<<it->second<<endl;
cout<<endl;
it=h.begin();
pair<int,int>p=*it;
h.erase(it);
cout<<"删除map容器h的第一个键值对:"<<endl;
cout<<p.first<<' '<<p.second<<endl<<endl;
cout<<"map容器h的元素个数为:"<<h.size()<<endl;
return 0;
}
[]操作符
h[key]返回key映射到的value的引用
可以很方便的通过h[key]来得到key对应的value值,还可以对h[key]进行赋值操作,来改变key对应的value
如果查找的key不存在,执行h[key]后,则会新建一个二元组<key,zero>,并返回zero的引用,zero代表0值
经典使用:
统计单词(字符串)出现的次数:
#include<map>
#include<cstdio>
#include<string>
#include<iostream>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
string str;
map<string,int>h;
for(int i=0;i<n;i++){
cin>>str;
h[str]++;
}
for(int i=0;i<m;i++){
cin>>str;
if(h.find(str)==h.end())
printf("0\n");
else
printf("%d\n",h[str]);
}
return 0;
}
/*
8 3
she is a girl
he is a boy
she
am
a
*/