map 是“關鍵字——值”對的集合。即
map<index, value>
其中 index 和 value 可以是各種類型,如 int, char, string,甚至是 STL 容器對象。
map 中的元素默認按 index 的增序進行排序,故要求 index 能夠進行排序,這也意味着 map 中不存在兩個元素擁有相同的 index。
定義
map<string,int> map_1;
初始化
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
添加元素
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.insert({ "she", 3 });
map 還有一個默認的機制:當我們通過下標訪問 map 對象中並不存在的一個 index 對應的 value 時,訪問並不會出錯,該 map 對象會自動添加一個元素,其 index 爲想要訪問的值,value 爲 value 類型的默認值
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } }; cout << map_1["she"];//輸出:0 map_1["it"]++; cout << map_1["it"];//輸出:1
刪除元素
map.erase(index):刪除以 index 爲索引的元素
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.erase("I");//map_1 = { { "you", 2 }, { "he", 3 } };
map.erase(p):刪除迭代器 p 指向的元素
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.erase(map_1.begin());//map_1 = { { "you", 2 }, { "he", 3 } };
map.erase(b, e):刪除由迭代器 b 和迭代器 e 所指向的範圍內的元素
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1.erase(map_1.begin(), map_1.begin()+2);//map_1 = { { "he", 3 } };
修改元素
與傳統的數組類似,map 可以修改指定 index 所對應的 value。
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
map_1["I"] = 2;//map_1 = { { "I", 2 }, { "you", 2 }, { "he", 3 } };
訪問元素
1、使用下標訪問
不同於傳統的數組,map 對象能以任何可排序的類型作爲 index,來訪問某個 index 所對應的值。這也是 map 容器最大的用處。
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
cout << map_1["you"];//輸出:2
若不想使用該特性,可使用 set.at(index) 來訪問 map 對象中 index 對象的值,此時,當 map 對象中不存在該 index 時,會拋出一個 out_of_range 的異常。
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } }; cout << map_1.at("you");//輸出:2 cout << map_1.at("she");//錯誤
如果既不想在訪問的 index 不在 map 對象中時使用其自動添加的功能,又不想在 map 對象中不存在該 index 時產生一個異常,則可以使用 find(),此函數在 map 對象中不存在欲訪問的 index 時會返回 map 對象的尾後迭代器。
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } }; auto it_1 = map_1.find("I");//it_1 = map_1.begin(); auto it_2 = map_1.find("she");//it_2 = map_1.end();
2、使用迭代器訪問
使用迭代訪問 map 對象中的元素需要注意的是,此時迭代解引用後得到的元素並不是 value,而是 pair<index, value>
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
auto it = map_1.begin() + 1;
cout << it->first;//輸出:you
cout << it->second;//輸出:2
遍歷元素
1、使用迭代器進行遍歷
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
for(auto it=map_1.begin(); it!=map_1.end(); map_1++)
cout << it->second << " ";
//輸出:1 2 3
2、使用 C11 新特性進行遍歷
map<string, int> map_1 = { { "I", 1 }, { "you", 2 }, { "he", 3 } };
for(auto p:map_1)
cout << p.second << " ";
//輸出:1 2 3