c++中的unordered_map如何使用
时间: 2023-08-21 19:17:13 浏览: 53
unordered_map是C++标准库中的一个容器,用于存储键值对,它提供了基于哈希表的快速查找功能。使用unordered_map需要包含头文件<unordered_map>。
下面是unordered_map的基本用法示例:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
// 创建一个unordered_map
std::unordered_map<std::string, int> umap;
// 添加键值对
umap["apple"] = 3;
umap["banana"] = 5;
umap["orange"] = 2;
// 访问值
std::cout << "The value of apple is: " << umap["apple"] << std::endl;
// 遍历unordered_map
for (const auto& pair : umap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
// 检查key是否存在
if (umap.find("banana") != umap.end()) {
std::cout << "The key 'banana' exists in the unordered_map." << std::endl;
}
// 删除键值对
umap.erase("orange");
// 清空unordered_map
umap.clear();
return 0;
}
```
在上面的示例中,我们创建了一个unordered_map对象umap,并添加了几个键值对。使用方括号运算符可以访问和修改值。通过遍历unordered_map,我们可以访问所有的键值对。可以使用find函数来检查某个键是否存在,并使用erase函数删除键值对。最后,使用clear函数清空unordered_map。
unordered_map还提供了其他一些常用的方法和操作,你可以查阅C++标准库的文档来了解更多信息。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)