在寫leetcode時參考別人範例使用unordered_map從而來回顧一下:
通常使用時機是要用hash table時,map容器會很好使用。
一、map簡介
他是c++ STL(standard template library)的一個class,是一種容器(如vector等),具有一對一mapping功能。
二、map格式與用法
1.格式
map<data_typeA, data_typeB>test
data_typeA:是一個index的角色,在map中,每個index只能在其中出現一次不能重複。
data_typeB:是data_typeA index所對應的資料。
2.操作(operation)
使用前要先include:
#include<map>
map<string,int>test;
接著 簡單的insert動作:
// 用 insert 函數插入 pair
test.insert(pair<string, int>("one", 1));
//用 "array" 方式插入
test["two"] = 2;
test["three"] = 3;
這裡有用到pair,是在<utility>的header中(此header也包含常用的swap),pair是一個Template,他把兩個物件裝在一起,如pair<int, bool>就是把一個int和一個bool裝在一起。
再來是取值:
cout << m["one"] << endl; // 1
cout << m["three"] << endl; // 3
cout << m["ten"] << endl; // 0 (無對應值)
還有尋找:
map<string,int>::iterator iter;
iter = mapStudent.find("r123");
iter = test.find("jason");
if (iter != test.end())cout<<"find";
else cout<<"not found";
cout<<test.count("one");
這裡的find(),若找到()中的值,就返回他所在位址,反之返回end()的位址。
而count則是若存在()中的index返回1,否則0
註1:.end()是容器最尾端的元素的下一個位置,請注意它不是最末元素。
註2:iterator有點像容器指標的概念 (請參考:http://larry850806.github.io/2016/06/06/STL2/)
最後是刪除與清空操作:
清空map用clear(),判斷map中是否有資料,可以使用empty(),而資料刪除用erase()
//迭代器刪除
iter = test.find("one");
test.erase(iter);
//用關鍵字刪除
int n = test.erase("one");//如果刪除了會返回1,否則返回0
//用迭代器範圍刪除 : 把整個map清空
test.erase(test.begin(), test.end());
//等同於mapStudent.clear()
三、延伸
- map : 紅黑樹 (查询、插入、删除都是O(logn) )
- unordered_map : hash 結構,C++11 標準函式庫。
- unordered_set : hash 結構,但 value 本身即是 key。
- hash_map : hash 結構,非標準函式庫。
有任何疑問或是有寫錯請多多指教~。
參考連結:
http://mropengate.blogspot.tw/2015/12/cc-map-stl.html
http://larry850806.github.io/2016/06/06/STL2/
http://blog.sina.com.cn/s/blog_61533c9b0100fa7w.html