STL整理之map
转载请注明出处,部分内容引自李煜东《算法竞赛进阶指南》
前置知识: C++ 、C 语言入门
Map 是什么
Map是从键(key )到值(value )的映射,其内部实现是一棵以key 为关键码的红黑树
Map 的相关操作
头文件
#include<map>
声明:
像这样:
map<key的类型,value的类型>名称;
比如:
map<long long,bool>mp;
map<string,int>mp;
map<pair<int,int>,vector<int>>mp;
就像其他需要排序的数据类型一样,
struct pos{
int x,y,s;
string move[100];
};
map<pos,int>mp;
bool operator <(const pos &ai,const pos &bi)
{
return (ai.x==bi.x)?ai.y>bi.y:ai.x>bi.x;
}
[]运算符
[]操作符是
若查找的
eg.
map<string,int>mp;
for(int i=1;i<=n;i++)
{
string s;
int num;
cin>>s>>num;
mp[s]=num;
}
for(int i=1;i<=m;i++)
{
string s;
cin>>s;
cout<<mp[s]<<endl;
}
map.size()
统计
用法:名称.size();
eg.
int num=mp.size();
map.empty()
检查
用法:名称.empty();
eg.
if(mp.empty())
cout<<"Mymap is Empty."<<endl;
map.clear()
清空
用法:名称.clear();
eg.
mp.clear();
map.count(x)
返回
用法:名称.count(x)
eg.
if(!mp.count(x))
mp[x]=1;
迭代器
双向访问迭代器,不支持随机访问,支持星号解除引用,仅支持“++”,“--”这两个算术操作
引用和操作:
map<类型,类型>::iterator it;
eg.
map<int,int>::iterator it=mp.begin();
it++;
it--;
若把
“++”,“--”操作的复杂度均为
对
遍历map 及访问其中的元素
for(map<int,int>::iterator it=mp.begin();it!=mp.end();it++)
if(it->second==ans) //访问二元组中第二个,即value
cout<<it->first<<endl; //访问key
map.find(x)
在
用法:名称.find(x);
eg.
if(mp.find(s)!=mp.end())
cout<<"Have Found!"<<endl;
map.insert(pair<...,...>)
在
PS:
用法:名称.insert(pair<key的类型,value的类型>);
eg.
mp.insert(make_pair(2,3));
map.erase( 参数)
删除,参数可以是
用法:名称.erase(参数);
eg.
map<int,int>::iterator it=mp.begin();
mp.erase(it);
mp.erase(make_pair(2,3));