c++ 判断键是否在unordered_map中
时间: 2023-07-26 13:38:42 浏览: 65
可以使用 `unordered_map` 的 `find()` 函数来判断键是否在 `unordered_map` 中。该函数返回一个迭代器,如果键存在于 `unordered_map` 中,则返回指向该键值对的迭代器,否则返回指向 `unordered_map` 结尾的迭代器。以下是一个示例代码:
```c++
#include <iostream>
#include <unordered_map>
int main() {
std::unordered_map<std::string, int> myMap = {
{"apple", 1},
{"banana", 2},
{"orange", 3}
};
// 判断键是否存在于 unordered_map 中
if (myMap.find("apple") != myMap.end()) {
std::cout << "apple exists in the unordered_map." << std::endl;
} else {
std::cout << "apple does not exist in the unordered_map." << std::endl;
}
if (myMap.find("watermelon") != myMap.end()) {
std::cout << "watermelon exists in the unordered_map." << std::endl;
} else {
std::cout << "watermelon does not exist in the unordered_map." << std::endl;
}
return 0;
}
```
输出结果为:
```
apple exists in the unordered_map.
watermelon does not exist in the unordered_map.
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)