unordered_map怎么使用
时间: 2023-05-22 20:01:56 浏览: 66
unordered_map是C++ STL中的一个容器,用于存储键值对。使用unordered_map需要包含头文件<unordered_map>。以下是一个简单的例子:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap;
// 添加键值对
myMap["apple"] = 1;
myMap["banana"] = 2;
myMap["orange"] = 3;
// 访问键值对
std::cout << "apple: " << myMap["apple"] << std::endl;
// 遍历键值对
for (auto& pair : myMap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
return 0;
}
```
输出:
```
apple: 1
banana: 2
orange: 3
```
在这个例子中,我们创建了一个unordered_map,键是字符串,值是整数。我们添加了三个键值对,然后访问了其中一个键的值。最后,我们使用一个循环遍历了所有的键值对。
相关问题
unordered_map 使用
unordered_map是C++ STL中的一个关联容器,它提供了一种将键映射到值的方法。它的使用方法类似于map,但是它内部实现了哈希表,因此查找速度是常量级别的。以下是unordered_map的使用方法:
1. 头文件引入
```c++
#include <unordered_map>
```
2. 创建unordered_map对象
```c++
std::unordered_map<std::string, int> myMap;
```
3. 插入元素
```c++
myMap.insert(std::make_pair("apple", 1));
myMap["banana"] = 2;
```
4. 访问元素
```c++
std::cout << myMap["apple"] << std::endl; // 输出:1
```
5. 查找元素
```c++
if (myMap.find("apple") != myMap.end()) {
std::cout << "Found apple!" << std::endl;
}
```
6. 删除元素
```c++
myMap.erase("apple");
```
unordered_map使用
unordered_map是C++ STL中的一个容器,用于实现哈希表,其可以用来存储键值对。使用unordered_map需要包含头文件<unordered_map>。
下面是unordered_map的使用示例:
```C++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
// 创建一个unordered_map对象
unordered_map<string, int> umap;
// 插入键值对
umap.insert(make_pair("apple", 3));
umap.insert(make_pair("orange", 5));
umap["banana"] = 2;
// 访问元素
cout << "The value of apple is " << umap["apple"] << endl;
cout << "The value of orange is " << umap["orange"] << endl;
cout << "The value of banana is " << umap["banana"] << endl;
// 查找元素
if (umap.find("pear") != umap.end()) {
cout << "The value of pear is " << umap["pear"] << endl;
}
else {
cout << "Pear not found" << endl;
}
// 遍历unordered_map
for (auto it = umap.begin(); it != umap.end(); it++) {
cout << it->first << ": " << it->second << endl;
}
return 0;
}
```
输出结果:
```
The value of apple is 3
The value of orange is 5
The value of banana is 2
Pear not found
banana: 2
apple: 3
orange: 5
```
在上面的示例中,我们创建了一个字符串到整数的unordered_map对象umap,并插入了三个键值对。我们可以使用[]运算符访问元素,使用find()方法查找元素。我们还可以使用迭代器遍历unordered_map中的所有元素。