unordered_map
时间: 2023-10-13 18:24:39 浏览: 39
The unordered_map is an associative container in C++ STL that stores key-value pairs. It is implemented using hash table data structure and provides constant time complexity for most of its operations.
Some important features of unordered_map are:
1. It stores unique keys and corresponding values.
2. The keys are hashed to store and access values efficiently.
3. It provides constant time complexity for insertion, deletion, and search operations.
4. It does not maintain any order of the elements.
5. It supports various operations like find, insert, erase, size, and clear.
Example:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> umap;
// Inserting key-value pairs
umap.insert(std::make_pair("John", 25));
umap.insert(std::make_pair("Alice", 30));
umap.insert(std::make_pair("Bob", 27));
umap.insert(std::make_pair("Charlie", 35));
// Accessing value using key
std::cout << "Age of Bob: " << umap["Bob"] << std::endl;
// Iterating over all key-value pairs
for (auto it = umap.begin(); it != umap.end(); it++) {
std::cout << it->first << " : " << it->second << std::endl;
}
// Erasing key-value pair using key
umap.erase("Charlie");
// Checking if key exists
if (umap.find("Alice") != umap.end()) {
std::cout << "Alice is present in the map" << std::endl;
}
return 0;
}
```
Output:
```
Age of Bob: 27
Charlie : 35
Bob : 27
John : 25
Alice : 30
Alice is present in the map
```