c++ 判断unordered map判断元素是否存在
时间: 2023-07-26 07:27:18 浏览: 85
在C++中,我们可以使用`unordered_map`的`count`方法来判断元素是否存在。`count`方法返回一个整数值,表示指定键值所对应的元素在`unordered_map`中出现的次数。如果该元素存在,则返回1;如果不存在,则返回0。下面是一个示例代码:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main()
{
unordered_map<int, string> myMap = {{1, "apple"}, {2, "banana"}, {3, "orange"}};
if (myMap.count(2))
{
cout << "Element with key 2 exists in the map" << endl;
}
else
{
cout << "Element with key 2 does not exist in the map" << endl;
}
if (myMap.count(4))
{
cout << "Element with key 4 exists in the map" << endl;
}
else
{
cout << "Element with key 4 does not exist in the map" << endl;
}
return 0;
}
```
输出结果为:
```
Element with key 2 exists in the map
Element with key 4 does not exist in the map
```
在上面的示例代码中,我们使用`count`方法来判断`myMap`中是否存在键值为2和4的元素,输出相应的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![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)