unordered_map的用法举例
时间: 2023-04-09 16:04:45 浏览: 57
unordered_map是C++ STL中的一个容器,用于存储键值对,其中键和值可以是任意类型。以下是一个unordered_map的用法举例:
```c++
#include <iostream>
#include <unordered_map>
#include <string>
int main() {
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 5;
myMap["banana"] = 2;
myMap["orange"] = 3;
std::cout << "The number of apples is: " << myMap["apple"] << std::endl;
std::cout << "The number of bananas is: " << myMap["banana"] << std::endl;
std::cout << "The number of oranges is: " << myMap["orange"] << std::endl;
return 0;
}
```
输出结果为:
```
The number of apples is: 5
The number of bananas is: 2
The number of oranges is: 3
```
在这个例子中,我们创建了一个unordered_map,键是字符串类型,值是整数类型。我们向这个unordered_map中添加了三个键值对,然后通过键来访问对应的值。