map映射
A map is a generalized array that consists of key-value-pairs. While the keys in an ordinary array are always the consecutive integers 0, 1 ,... , n−1
, where n is the size of the array, the keys in a map can be of any data type and they do not have to be consecutive values.
map<string,int> m;
m["monkey"] = 4;
m["banana"] = 3;
m["apple"] = 9;
cout << m["banana"] << "\n"; // 3
If the value of a key is requested but the map does not contain it, the key is automatically added to the map with a default value. For example, in the following code, the key ”aybabtu” with value 0 is added to the map.
map<string,int> m;
cout << m["aybabtu"] << "\n"; // 0
所以,上述这个操作,不是很好,当查询次数很多,会造成空间问题(我在 CF 现场比赛中,真实遇见…,当时还不熟练这个操作)
// 判断是否存在,用count
if (m.count("aybabtu")) {
// key exists
}
// C++11的遍历,我们自己写,要用interator
for (auto x : m) {
cout << x.first << " " << x.second << "\n";
}
//所以,我想问,能不能 map<int, string> ????