How to use map in C++?

In C++, std::map is an associative container that provides a way to store key-value pairs. Here is a basic usage of std::map:

  1. Include header file:
#include <map>
  1. a data structure in C++ called map
std::map<KeyType, ValueType> myMap;

The KeyType here refers to the type of key, while ValueType refers to the type of value.

  1. Add in the information.
  2. Please rephrase the following sentence in natural English, you only need to provide one option.
myMap.insert(std::make_pair(key, value));
// 或者
myMap[key] = value;
  1. Please rephrase the following sentence in your own words.
ValueType value = myMap[key];

Note that if the key does not exist, the above operation will insert a new key-value pair.

  1. locate
std::map<KeyType, ValueType>::iterator it = myMap.find(key);
if (it != myMap.end()) {
    // 找到了元素
    ValueType value = it->second;
} else {
    // 没有找到元素
}
  1. delete
myMap.erase(key);
  1. Standard map data structure
for (std::map<KeyType, ValueType>::iterator it = myMap.begin(); it != myMap.end(); ++it) {
    KeyType key = it->first;
    ValueType value = it->second;
    // 使用 key 和 value 进行操作
}

The above is the basic usage of std::map, there are also other advanced usages that can be further explored.

bannerAds