C++ Map Guide: std::map & unordered_map
Maps in C++ can be implemented using std::map or std::unordered_map, which are located in the
When using std::map, include the header file and declare and initialize a map using the following syntax:
std::map<KeyType, ValueType> myMap;
KeyType indicates the type of the key, while ValueType indicates the type of the value.
When using std::unordered_map, you need to include the
std::unordered_map<KeyType, ValueType> myMap;
Similarly, KeyType represents the type of key, while ValueType represents the type of value.
Common operations of a mapping table include inserting, searching, and deleting elements, with specific methods as follows:
- Insert element:
myMap.insert(std::make_pair(key, value));
// 或者
myMap[key] = value;
- Search for elements.
if (myMap.find(key) != myMap.end()) {
// 元素存在
ValueType value = myMap[key];
} else {
// 元素不存在
}
- Remove elements.
myMap.erase(key);
Additionally, you can also use an iterator to traverse all elements of the map.
for (auto it = myMap.begin(); it != myMap.end(); ++it) {
KeyType key = it->first;
ValueType value = it->second;
// 处理元素
}
These are the basic uses of mapping tables, and depending on specific needs, other functions such as modifying element values and obtaining the size of the mapping table can also be utilized.