std::unordered_map 怎么查找
时间: 2023-04-04 14:02:45 浏览: 59
std::unordered_map 可以使用 find() 函数进行查找,例如:
std::unordered_map<std::string, int> myMap;
myMap["apple"] = 1;
myMap["banana"] = 2;
auto it = myMap.find("apple");
if (it != myMap.end()) {
std::cout << "apple is found with value " << it->second << std::endl;
} else {
std::cout << "apple is not found" << std::endl;
}
输出结果为:
apple is found with value 1
相关问题
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是C++标准库中的一个关联容器,它可以存储一组键值对,并且支持快速的查找、插入和删除操作。
以下是一个使用std::unordered_map的示例代码:
```cpp
#include <unordered_map>
#include <iostream>
int main() {
std::unordered_map<int, std::string> umap;
// 插入键值对
umap.insert(std::make_pair(1, "apple"));
umap.insert(std::make_pair(2, "banana"));
umap.insert(std::make_pair(3, "orange"));
// 查找键值对
int key = 2;
auto it = umap.find(key);
if (it != umap.end()) {
std::cout << "Key " << key << " found, value is " << it->second << std::endl;
} else {
std::cout << "Key " << key << " not found" << std::endl;
}
// 删除键值对
umap.erase(3);
// 遍历键值对
for (const auto& pair : umap) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
```
这段代码创建了一个std::unordered_map对象umap,插入了三个键值对,然后通过find函数查找指定的键值对,最后删除了一个键值对,并遍历输出了所有的键值对。