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.

  1. map<string,int> m;
  2. m["monkey"] = 4;
  3. m["banana"] = 3;
  4. m["apple"] = 9;
  5. 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.

  1. map<string,int> m;
  2. cout << m["aybabtu"] << "\n"; // 0

所以,上述这个操作,不是很好,当查询次数很多,会造成空间问题(我在 CF 现场比赛中,真实遇见…,当时还不熟练这个操作)

  1. // 判断是否存在,用count
  2. if (m.count("aybabtu")) {
  3. // key exists
  4. }
  5. // C++11的遍历,我们自己写,要用interator
  6. for (auto x : m) {
  7. cout << x.first << " " << x.second << "\n";
  8. }
  1. //所以,我想问,能不能 map<int, string> ????

std::map

https://www.cplusplus.com/reference/map/map/?kw=map
image.png
image.png