How is the std map used in C++?
In C++, std::map is an associative container that stores a collection of key-value pairs in a sorted manner. It is implemented based on a red-black tree, providing efficient operations for searching, inserting, and deleting elements.
When using std::map, you need to include the header file. The syntax for creating a map object is as follows:
std::map<Key, Value> mapName;
Key represents the type of key, Value represents the type of value, and mapName is the name of the map object.
You can insert key-value pairs into a map using the insert() function.
mapName.insert(std::pair<Key, Value>(key, value));
You can also use the subscript operator [] to insert key-value pairs:
mapName[key] = value;
You can use the find() function to search for the value of a specified key:
std::map<Key, Value>::iterator it = mapName.find(key);
if (it != mapName.end()) {
// 键存在,可以通过it->second访问对应的值
} else {
// 键不存在
}
You can use the erase() function to delete key-value pairs of a specific key.
mapName.erase(key);
You can use the clear() function to remove all key-value pairs from a map.
mapName.clear();
You can traverse the entire map using an iterator.
for (std::map<Key, Value>::iterator it = mapName.begin(); it != mapName.end(); ++it) {
// 可以通过it->first访问键,通过it->second访问值
}
It is important to note that in std::map, keys are unique, and if you insert a duplicate key, it will overwrite the original value. If you need to store key-value pairs with duplicate keys, you can use std::multimap.