STL:map用法總結

蝸牛201發表於2018-10-30

一:介紹

map是STL的關聯式容器,以key-value的形式儲存,以紅黑樹(平衡二叉查詢樹)作為底層資料結構,對資料有自動排序的功能。
名稱空間為std,所屬標頭檔案<map>

二:常用操作

容量:
a.map中實際資料的資料:map.size()
b.map中最大資料的數量:map.max_size()
c.判斷容器是否為空:map.empty()

修改:
a.插入資料:map.insert()
b.清空map元素:map.clear()
c.刪除指定元素:map.erase(it)

迭代器:
a.map開始指標:map.begin()
b.map尾部指標:map.end() 注:最後一個元素的下一個位置,類似為NULL,不是容器的最後一個元素

三:儲存

 1     map<int, string> map1;
 2 
 3     //方法1:
 4     map1.insert(pair<int, string>(2, "beijing"));
 5     //方法2:
 6     map1[4] = "changping";
 7     //方法3:
 8     map1.insert(map<int, string>::value_type(1, "huilongguan"));
 9     //方法4:
10     map1.insert(make_pair<int, string>(3, "xierqi"));

四:遍歷

1     for (map<int, string>::iterator it=map1.begin(); it!=map1.end(); it++)
2     {
3         cout << it->first << ":" << it->second << endl;
4     }

五:查詢

 1     //方法1
 2     string value1 = map1[2];
 3     if (value1.empty())
 4     {
 5         cout << "not found" << endl;
 6     }
 7 
 8     //方法2
 9     map<int, string>::iterator it = map1.find(2);
10     if (it == map1.end())
11     {
12         cout << "not found" << endl;
13     }
14     else
15     {
16         cout << it->first << ":" << it->second << endl;
17     }

六:修改

map1[2] = "tianjin";

七:刪除

1     //方法1
2     map1.erase(1);
3 
4     //方法2
5     map<int, string>::iterator it1 = map1.find(2);
6     map1.erase(it1);

 

掃碼關注公眾號

專注分享Java,C/C++,STL,Spring框架,mybatis框架,mysql,redis,分散式,高併發,設計模式,爬蟲,docker,shell程式設計等相關技術,在這裡一起探討,一起學習,一起進步,不定期分享視訊書籍資源,充分利用碎片化時間,讓我們的技術之路更加有樂趣。