STL整理之map

转载请注明出处,部份内容引自李煜东《算法竞赛进阶指南》
 算法



前置知识:    C++、C语言入门

函数



Map是什么spa


Map是从键(key)到值(value)的映射,其内部实现是一棵以key为关键码的红黑树code


Map的相关操做blog


头文件排序

 

#include<map>


声明:ci


像这样:string

map<key的类型,value的类型>名称; 好比: map<long long,bool>mp; map<string,int>mp; map<pair<int,int>,vector<int>>mp;

就像其余须要排序的数据类型同样,key为一个结构体的map,须要重载小于号it

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; }


[]运算符入门


map重载了[]运算符,map[key]返回key到value的引用,时间复杂度O(log n)
[]操做符是map最吸引人的地方。咱们能够很方便地经过map[key]来获得key对应的value,还能够对map[key]进行赋值操做,改变key对应的value。
若查找的key不存在,则执行map[key]后,map会自动新建一个二元组(key,zero),并返回zero的引用。

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()


统计map中元素个数,函数返回一个整形变量,表示map中元素个数,时间复杂度O(1)

用法:名称.size(); eg. int num=mp.size();


map.empty()


检查map是否为空,返回一个bool型变量,1表示map为空,不然为非空,时间复杂度O(1)

用法:名称.empty(); eg. if(mp.empty()) cout<<"Mymap is Empty."<<endl;


map.clear()


清空map,无返回值

用法:名称.clear();
eg.
mp.clear();


map.count(x)


返回map中key为x的元素个数,时间复杂度为O(log n)

用法:名称.count(x) eg. if(!mp.count(x)) mp[x]=1;


迭代器


双向访问迭代器,不支持随机访问,支持星号解除引用,仅支持“++”,“--”这两个算术操做


引用和操做:

map<类型,类型>::iterator it; eg. map<int,int>::iterator it=mp.begin(); it++; it--;

若把it++,则it将会指向“下一个”元素。这里的下一个是指在key从小到大排序的结果中,排在it下一名的元素。同理,若把it--,则it会指向排在上一个的元素
“++”,“--”操做的复杂度均为O(log n)
对map的迭代器解除引用后,将获得一个二元组pair<...,...>

遍历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)


在map中查找key为x的二元组,并返回指向该二元组的迭代器,若不存在,返回map.end(),时间复杂度为O(log n)

用法:名称.find(x); eg. if(mp.find(s)!=mp.end()) cout<<"Have Found!"<<endl;


map.insert(pair<...,...>)


在map中插入,参数是pair<key.type,value.type>,返回插入地址的迭代器和是否插入成功的bool并成的pair,时间复杂度为O(log n)
PS:insert在进行插入的时候是不容许有重复的键值的,若是新插入的键值与原有的键值重复则插入无效

用法:名称.insert(pair<key的类型,value的类型>); eg. mp.insert(make_pair(2,3));


map.erase(参数)


删除,参数能够是pair或者迭代器,返回下一个元素的迭代器,时间复杂度为O(log n)

用法:名称.erase(参数); eg. map<int,int>::iterator it=mp.begin(); mp.erase(it); mp.erase(make_pair(2,3));
相关文章
相关标签/搜索