unordered_map
时间: 2023-10-12 13:09:42 浏览: 53
unordered_map is a container in C++ STL (Standard Template Library) that stores elements in a key-value pair format. It is implemented using a hash table, which makes it very efficient for lookup, insertion, and deletion operations. The keys in an unordered_map are unique, and the elements are sorted based on their hash values.
The syntax for declaring an unordered_map is as follows:
```c++
std::unordered_map <key_type, value_type> map_name;
```
Here, key_type is the data type of the key, and value_type is the data type of the value. For example, if we want to create an unordered_map of string keys and integer values, we can use the following syntax:
```c++
std::unordered_map <std::string, int> my_map;
```
We can insert elements into the unordered_map using the insert() function:
```c++
my_map.insert(std::make_pair("apple", 10));
```
We can access the value associated with a particular key using the [] operator:
```c++
int value = my_map["apple"];
```
We can also iterate over the elements of the unordered_map using iterators:
```c++
for(auto it = my_map.begin(); it != my_map.end(); ++it) {
std::cout << it->first << " : " << it->second << std::endl;
}
```
Overall, unordered_map provides a fast and efficient way of storing and accessing key-value pairs in C++.