stl之map
0 简介
Map
Maps are associative containers that store elements formed by a combination of a key value and a mapped value, following a specific order.
In a map, the key values are generally used to sort and uniquely identify the elements, while the mapped values store the content associated to this key. The types of key and mapped value may differ, and are grouped together in member type value_type, which is a pair type combining both:
|
|
Internally, the elements in a map are always sorted by its key following a specific strict weak ordering criterion indicated by its internal comparison object (of type Compare).
map containers are generally slower than unordered_map containers to access individual elements by their key, but they allow the direct iteration on subsets based on their order.
The mapped values in a map can be accessed directly by their corresponding key using the bracket operator ((operator[]).
Maps are typically implemented as binary search trees.
1 使用
1.1 头文件
#include<map>
1.2 定义
map<int,string>my_map1 ; multimap<string,string>my_map2 ;
其中第一个是key value,第二个是mapped value。
也可嵌套定义
map<int,map<string,long> > my_map3 ;
>与>之间须有空格。
2 函数
2.1 插入的三种方法
mymap.insert( pair<int,string> (1,"neko") ); //方式一:用insert函数插入pair对象 mymap.insert(map<int,string>::value_type(2,"gee")); //方式二 :用insert函数插入value_type对象 mymap[3] = "kk" ; //方式三 : 用数组方式插入值
数组方式非常直观,但存在一个性能的问题。插入2时,先在enumMap中查找主键为2的项,没发现,然后将一个新的对象插入enumMap,键是2,值是一个空字符串,插入完成后,将字符串赋为"Two"; 该方法会将每个值都赋为缺省值(默认值),然后再赋为显示的值,如果元素是类对象,则开销比较大。
mymap.insert(pair<int,string>(2,"neko")); mymap.insert(pair<int,string>(2,"b"));
2对应的值仍是neko。
mymap[3]="neko"; mymap[3]="gee";
3对应的值neko被gee覆盖。
map的一个key只能对应一个value,而multimap可以有多个相同的key对应不同value。举个例子,map就是一个作者只对应一本书,而multimap一个作者可对应多本书。
2.2 大小
mymap.size()
返回元素个数
2.3 遍历
a.(前向)迭代器
map <int,string>::iterator iter ; for ( iter = mymap.begin() ; iter != mymap.end() ; ++iter ) { cout << iter->first <<" "<<iter->second<<endl ; }
b. 数组方式(关键字按顺序时)
for ( int i = a ; i <= mymap.size() ; ++i ) //a为起始关键字 { cout << mymap[i] << endl ; }
2.4 查找关键字
a. count函数,找到返回1,否则返回0。
cout << mymap.count(1) <<endl ;
b. find函数,找到返回所在位置的迭代器,否则返回end位置的迭代器。
if( mymap.find(2) != mymap.end() ) { cout << mymap.find(2)->second <<endl ; } else { cout<< "failed!" << endl ; }
2.5 清空和判断是否为空
mymap.clear() 清空
mymap.empty() 空返回1,非空返回0
2.6 删除
mymap.erase(1); //删除关键字为1的 mymap.erase(mymap.find(1));//迭代器方式删除 mymap.erase(mymap.begin(),mymap.end());//删除一个范围内的元素
2.7 排序
map中的key自动按升序排列。
如需其他排列方式,要重载运算符。
3 基本操作函数总结
参考资料:http://www.cnblogs.com/fnlingnzb-learner/p/5833051.html
http://www.cplusplus.com/reference/map/map/?kw=map
http://baike.baidu.com/link?url=hVAdqK2RPk9MPqgbHLZ7VlPQYQlPfyVeiv4RMoYR97rdGDiMivGQgt_8kyNkzlTquQpBJHcy71nwlI9qEjullJYdPRwV94dV8j6_dDpB-am

浙公网安备 33010602011771号