unordered_map c++
时间: 2023-10-20 12:34:28 浏览: 155
unordered_map是C++标准库中的一个容器,用于存储键值对。它是一个无序的哈希表,可以快速插入、搜索和删除元素。
使用unordered_map时,需要包含头文件<unordered_map>。以下是一个示例代码:
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> umap;
// 向unordered_map中插入键值对
umap.emplace("key1", 1);
umap.emplace("key2", 2);
umap.emplace("key3", 3);
// 通过键来访问值
std::cout << "The value of key1 is: " << umap["key1"] << std::endl;
// 遍历unordered_map中的所有键值对
for (auto it = umap.begin(); it != umap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
在上述代码中,我们首先创建了一个unordered_map对象umap,它的键类型为std::string,值类型为int。然后使用emplace函数插入了三个键值对。通过umap["key1"]可以获取到键为"key1"的值。最后使用循环遍历了整个unordered_map,输出了所有键值对的内容。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [C++中的unordered_map用法详解](https://blog.csdn.net/leduoduodeai/article/details/127506165)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.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)