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:
- Include header file:
#include <map>
- 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.
- Add in the information.
- 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;
- 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.
- locate
std::map<KeyType, ValueType>::iterator it = myMap.find(key);
if (it != myMap.end()) {
// 找到了元素
ValueType value = it->second;
} else {
// 没有找到元素
}
- delete
myMap.erase(key);
- 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.