Last Updated on 2021-11-02 by Clay
map 是 C++ 標準模板函式庫(Standard Template Library, STL)中的關聯容器(Associative Container),也就是存在著 key-value 這樣對應關係的一種容器。
這種 key-value 的對應關係為一對一映射(one-to-one mapping),每一個 key 都只在 map 物件中出現一次,每一個 key 都只對應一個特定的值。如果不小心重新插入了新的 key,那麼抱歉,原先的 key 就會被新的覆蓋掉。
而在 C++ 中,map 是使用紅黑樹來實作、unodrdered_map 則是用雜湊(hash)結構來實作。
那麼,以下就簡單紀錄,該如何使用標準函式庫中的 map。
map 使用方法筆記
首先來看個最簡單的例子:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
map<string, int> map_data = {
{"Clay", 26},
{"Atlas", 25},
{"Mary", 19},
};
for (auto &m: map_data) {
cout << m.first << ": "<< m.second << endl;
}
return 0;
}
Output:
Atlas: 25
Clay: 26
Mary: 19
這是一個最最簡單的例子。我們先宣告了 map<string, int> 的變數 map_data,代表這個 map 容器的 key-value 其資料型態分別為 string 以及 int —— 簡單來講,就是一組字串映射到一個整數。
然後下方我使用 &m 將 map 容器中的數值取出,其中:
- m.first 代表著 key
- m.second 代表著 value
是不是很單純呢?
insert()
當然,我們可以在建立好 map 容器後,再依照自己的需求使用 insert()
函式插入新的 key-value 資料。
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
// Init
map<string, int> map_data = {
{"Clay", 26},
{"Atlas", 25},
{"Mary", 19},
};
// Insert
map_data.insert(pair<string, int>("Zack", 35));
// Print
for (auto &m: map_data) {
cout << m.first << ": "<< m.second << endl;
}
return 0;
}
Output:
Atlas: 25
Clay: 26
Mary: 19
Zack: 35
insert()
中要插入的物件同樣需要使用 pair 指定資料型態。
find()
若我們需要查看某筆資料是否存在 map 容器中,可以使用 find()
函式來查找,查找的結果分成以下兩類:
- 找到: 返回命中資料所在位置。
- 沒找到: 返回指向 end() 位置。
以下來看個簡單的範例:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
// Init
map<string, int> map_data = {
{"Clay", 26},
{"Atlas", 25},
{"Mary", 19},
};
// find()
auto find_01 = map_data.find("Clay");
auto find_02 = map_data.find("John");
// Print
if (find_01 == map_data.end()) {
cout << "Not found!" << endl;
}
else {
cout << find_01->first << ": " << find_01->second << endl;
}
if (find_02 == map_data.end()) {
cout << "Not found!" << endl;
}
else {
cout << find_02->first << ": " << find_02->second << endl;
}
return 0;
}
Output:
Clay: 26
Not found!
可以發現,存在於 map_data 中的 Clay 找得到,而不存在的 John 則找不到。
erase()
能夠插入資料、尋找資料外,map_data 當然也可以使用 erase()
函式刪除指定的資料,而且若是配合 find()
函式則更加方便。
比方說我們要刪除掉 key 為 Clay 的這筆資料:
#include <iostream>
#include <string>
#include <map>
using namespace std;
int main() {
// Init
map<string, int> map_data = {
{"Clay", 26},
{"Atlas", 25},
{"Mary", 19},
};
// erase()
map_data.erase(map_data.find("Clay"));
// Print
for (auto &m: map_data) {
cout << m.first << ": " << m.second << endl;
}
return 0;
}
Output:
Atlas: 25
Mary: 19
除此之外,還有以下常用的函式:
empty()
: 確認 map 容器是否為空clear()
: 將 map 容器徹底清空
References
- https://www.freecodecamp.org/news/c-plus-plus-map-explained-with-examples/
- https://www.geeksforgeeks.org/map-associative-containers-the-c-standard-template-library-stl/
- https://www.cprogramming.com/tutorial/stl/stlmap.html