What is the purpose of unordered_map in C++?
The unordered_map is a container in the C++ standard library used to store key-value pairs. It functions similarly to a dictionary or hash table, allowing for quick retrieval of values based on keys.
unordered_map uses a hash table to implement it, which allows for fast lookup operations. Unlike the map container, unordered_map does not sort the keys in order, making it more efficient for lookup operations. It can be used in scenarios that require fast lookup of key-value pairs, such as counters and caches.
When using an unordered_map, both the key and value can be of any type, as long as they meet specific requirements. This map provides a range of member functions and operators that make it easy to insert, remove, access, and modify key-value pairs.
For example, the following code demonstrates the basic usage of unordered_map:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> map;
// 插入键值对
map.insert({1, "apple"});
map.insert({2, "banana"});
map.insert({3, "orange"});
// 访问和修改值
std::cout << map[1] << std::endl; // 输出: apple
map[1] = "kiwi";
std::cout << map[1] << std::endl; // 输出: kiwi
// 查找键值对
if (map.find(2) != map.end()) {
std::cout << "Found key 2: " << map[2] << std::endl; // 输出: Found key 2: banana
}
// 删除键值对
map.erase(3);
// 遍历所有键值对
for (const auto& pair : map) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
Output result:
apple
kiwi
Found key 2: banana
Key: 1, Value: kiwi
Key: 2, Value: banana
In conclusion, unordered_map offers an efficient way to store and look up key-value pairs, making it suitable for scenarios that require quick access and modification of data.