How to use unordered map in c++
时间: 2023-10-18 22:21:10 浏览: 48
The unordered_map container in C++ is used to store key-value pairs. It is similar to the map container, but the keys are not sorted. Here are the steps to use unordered_map in C++:
1. Include the unordered_map header file in your program.
```c++
#include <unordered_map>
```
2. Define an unordered_map variable with the desired key and value types.
```c++
std::unordered_map<std::string, int> myMap;
```
3. Add elements to the unordered_map using the insert() function.
```c++
myMap.insert({"apple", 3});
myMap.insert({"banana", 2});
myMap.insert({"orange", 4});
```
4. Access elements in the unordered_map using the [] operator or the find() function.
```c++
std::cout << myMap["apple"] << std::endl; // prints 3
auto it = myMap.find("banana");
if (it != myMap.end()) {
std::cout << it->second << std::endl; // prints 2
}
```
5. Iterate over the elements in the unordered_map using a range-based for loop.
```c++
for (const auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
```
Output:
```
orange: 4
banana: 2
apple: 3
```
Note: The unordered_map container is only available in C++11 and later versions. If you are using an older version of C++, you can use the std::tr1::unordered_map container from the <tr1/unordered_map> header file.