std::unordered_map include
时间: 2023-07-06 08:34:47 浏览: 44
To use std::unordered_map in C++, you need to include the <unordered_map> header file in your code. This header file defines the unordered_map template class and its associated functions and types. Here is an example of how to include it:
```c++
#include <unordered_map>
```
Once you have included this header file, you can start using the std::unordered_map class in your code.
相关问题
std::unordered_map查找
std::unordered_map是C++标准库中的一个关联容器,它提供了一种快速查找和插入键值对的方式。unordered_map使用哈希表来实现,因此查找操作的平均时间复杂度为O(1)。
要在unordered_map中进行查找,可以使用成员函数find()或者count()。find()函数返回一个迭代器,指向要查找的键值对,如果未找到,则返回unordered_map的end()迭代器。count()函数返回指定键的数量,如果存在则返回1,否则返回0。
以下是使用std::unordered_map进行查找的示例代码:
```cpp
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<int, std::string> myMap = {
{1, "apple"},
{2, "banana"},
{3, "orange"}
};
// 使用find()函数进行查找
auto it = myMap.find(2);
if (it != myMap.end()) {
std::cout << "Key found! Value is: " << it->second << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
// 使用count()函数进行查找
if (myMap.count(3) > 0) {
std::cout << "Key found!" << std::endl;
} else {
std::cout << "Key not found!" << std::endl;
}
return 0;
}
```
遍历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 (auto it = myMap.begin(); it != myMap.end(); ++it) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
return 0;
}
```
在上述代码中,我们首先创建了一个std::unordered_map对象myMap,并初始化了一些键值对。然后,我们使用for循环和迭代器来遍历myMap。迭代器it指向当前键值对,通过it->first和it->second可以获取键和值。