c++ unordered map
时间: 2023-11-06 12:08:01 浏览: 86
C++ 中的 unordered_map 是一种关联容器,它提供了基于键值对的快速查找功能。它的底层实现是哈希表,因此查找的时间复杂度为 O(1)。
使用 unordered_map 需要包含头文件 <unordered_map>,并且可以使用 std 命名空间。
下面是一个简单的例子:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> umap;
// 插入键值对
umap.insert({"apple", 1});
umap.insert({"banana", 2});
umap.insert({"cherry", 3});
// 查找键值对
std::cout << "apple: " << umap["apple"] << std::endl;
std::cout << "banana: " << umap["banana"] << std::endl;
std::cout << "cherry: " << umap["cherry"] << std::endl;
return 0;
}
```
输出结果为:
```
apple: 1
banana: 2
cherry: 3
```
相关问题
c++ unordered map遍历
在C++中,你可以使用范围循环(range-based for loop)来遍历`std::unordered_map`(无序映射)。下面是一个示例代码,展示了如何遍历一个`std::unordered_map`并打印出其中的键和值:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "apple"},
{2, "banana"},
{3, "orange"}
};
// 使用范围循环遍历unordered_map
for (const auto& pair : myMap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
```
在这个示例中,我们创建了一个`std::unordered_map`,其中键是整数,值是字符串。然后,我们使用范围循环来遍历这个无序映射。在每次循环中,`pair`被绑定到当前键值对,并可以通过`pair.first`和`pair.second`访问键和值。我们将它们打印出来。
运行这段代码,你会得到如下输出:
```
Key: 1, Value: apple
Key: 2, Value: banana
Key: 3, Value: orange
```
这样就完成了对`std::unordered_map`的遍历。范围循环使得代码更加简洁和易读。希望这个示例对你有帮助!如果你还有其他问题,请随时提问。
c++unorderedmap中count
在C++的unordered_map中,count函数用于判断某个键是否存在,返回值为0或1。其函数原型为:size_type count(const key_type& k) const; 例如,若umap为一个unordered_map对象,想要判断键"Python教程"是否存在,可以使用umap.count("Python教程"),若返回值为1,则表示该键存在,否则不存在。
阅读全文
相关推荐
![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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pptx](https://img-home.csdnimg.cn/images/20241231044947.png)