21xrx.com
2025-03-23 23:01:00 Sunday
文章检索 我的文章 写文章
如何判断C++ Map中的Key是否存在
2023-06-28 00:32:18 深夜i     75     0
C++ Map Key 判断 存在

C++中的Map容器是一种关联容器,它使用一对键值对来存储和访问数据。在C++中,Map容器中的每个键都必须是唯一的。但是,有时候我们需要检查一个特定的键是否存在于Map容器中。本文将介绍几种方法来判断C++ Map中的Key是否存在。

方法一:使用count函数

Map容器中提供了count函数,该函数返回指定键在Map容器中出现的次数。由于Map容器中每个键都必须是唯一的,如果count函数返回值为0,则表示该键不存在于Map容器中。

例如,我们可以通过以下代码来检查容器中是否存在名为"Bob"的键:

#include <iostream>
#include <map>
using namespace std;
int main() {
  map<string, int> myMap;
  myMap["Alice"] = 20;
  myMap["Charlie"] = 23;
  // 判断Bob键是否存在
  if (myMap.count("Bob"))
    cout << "Bob exists!" << endl;
  
  else
    cout << "Bob does not exist." << endl;
  
  return 0;
}

输出结果为:Bob does not exist.

方法二:使用find函数

Map容器中还提供了find函数,该函数返回指定键在Map容器中的迭代器。如果该键不存在,则返回Map容器的末尾迭代器。因此,我们可以判断find函数返回值是否等于Map容器的末尾迭代器来判断键是否存在于Map容器中。

例如,我们可以使用以下代码来检查容器中是否存在名为"Alice"的键:

#include <iostream>
#include <map>
using namespace std;
int main() {
  map<string, int> myMap;
  myMap["Alice"] = 20;
  myMap["Charlie"] = 23;
  // 判断Alice键是否存在
  if (myMap.find("Alice") != myMap.end())
    cout << "Alice exists!" << endl;
  
  else
    cout << "Alice does not exist." << endl;
  
  return 0;
}

输出结果为:Alice exists!

方法三:使用count和find结合使用

我们还可以将count函数和find函数结合使用来判断Map容器中的键是否存在。具体来说,我们可以使用count函数先判断键是否存在,如果存在,则使用find函数获取该键对应的迭代器,否则返回Map容器的末尾迭代器。

例如,我们可以使用以下代码来检查容器中是否存在名为"Charlie"的键:

#include <iostream>
#include <map>
using namespace std;
int main() {
  map<string, int> myMap;
  myMap["Alice"] = 20;
  myMap["Charlie"] = 23;
  // 判断Charlie键是否存在
  if (myMap.count("Charlie")) {
    auto it = myMap.find("Charlie");
    cout << "Charlie's age is " << it->second << endl;
  }
  else
    cout << "Charlie does not exist." << endl;
  
  return 0;
}

输出结果为:Charlie's age is 23

通过以上三种方法,我们可以很方便地判断C++ Map容器中的键是否存在。根据实际需求,选择相对应的方法进行使用即可。

  
  

评论区