c++判断字典中是否存在key
时间: 2023-11-26 15:02:42 浏览: 103
在 C++ 中,可以使用 std::map 来表示字典,其中的 key-value 对可以用 std::pair 类型来表示。
要判断一个 key 是否存在于字典中,可以使用 std::map 的 find() 方法。如果该方法返回字典的 end() 迭代器,则表示该 key 不存在于字典中;否则,返回的迭代器指向该 key 对应的 value。
以下是一个示例代码:
```cpp
#include <iostream>
#include <map>
#include <string>
int main() {
std::map<std::string, int> dict = { {"apple", 1}, {"banana", 2}, {"orange", 3} };
// 判断 key 是否存在
std::string key = "apple";
auto it = dict.find(key);
if (it != dict.end()) {
std::cout << "Key '" << key << "' exists, its value is " << it->second << std::endl;
} else {
std::cout << "Key '" << key << "' does not exist." << std::endl;
}
key = "pear";
it = dict.find(key);
if (it != dict.end()) {
std::cout << "Key '" << key << "' exists, its value is " << it->second << std::endl;
} else {
std::cout << "Key '" << key << "' does not exist." << std::endl;
}
return 0;
}
```
输出结果为:
```
Key 'apple' exists, its value is 1
Key 'pear' does not exist.
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)