21xrx.com
2024-06-02 23:41:34 Sunday
登录
文章检索 我的文章 写文章
C++ Map如何判断Key是否存在?
2023-07-07 08:33:29 深夜i     --     --
C++ Map Key 存在 判断

C++中的Map是一种常用的关联容器,它将键值对存储在一起,并允许用户轻松地查找特定的元素。在Map中,键是唯一的,如果用户想要判断一个键是否存在,可以使用以下两种方法来实现。

1. 使用count()函数

Map提供了一个count()函数,它返回指定键出现的次数。如果Map中不存在该键,则返回0,否则返回1。通过检查count()函数返回的值,可以判断Map中是否存在指定的键。下面是一个演示如何使用count()函数来判断一个键是否存在的例子:


#include <iostream>

#include <map>

using namespace std;

int main()

{

  map<string, int> mymap;

  mymap["John"] = 25;

  mymap["Bob"] = 30;

  if (mymap.count("John") > 0)

    cout << "John is in the map" << endl;

   else

    cout << "John is not in the map" << endl;

  

  if (mymap.count("Mike") > 0)

    cout << "Mike is in the map" << endl;

   else

    cout << "Mike is not in the map" << endl;

  

  return 0;

}

在上面的例子中,我们使用了count()函数来检查Map中是否有两个键:“John”和“Mike”。由于Map中存在“John”键,因此第一个if语句输出“John is in the map”。由于Map中不存在“Mike”键,所以第二个if语句输出“Mike is not in the map”。

2. 使用find()函数

Map也提供了一个find()函数,它返回指向指定键的迭代器。如果Map中不存在该键,则返回end()迭代器。通过检查find()函数返回的迭代器是否等于end()迭代器,可以判断Map中是否存在指定的键。下面是一个演示如何使用find()函数来判断一个键是否存在的例子:


#include <iostream>

#include <map>

using namespace std;

int main()

{

  map<string, int> mymap;

  mymap["John"] = 25;

  mymap["Bob"] = 30;

  if (mymap.find("John") != mymap.end())

    cout << "John is in the map" << endl;

   else

    cout << "John is not in the map" << endl;

  

  if (mymap.find("Mike") != mymap.end())

    cout << "Mike is in the map" << endl;

   else

    cout << "Mike is not in the map" << endl;

  

  return 0;

}

在上面的例子中,我们使用find()函数来检查Map中是否有两个键:“John”和“Mike”。由于Map中存在“John”键,因此第一个if语句输出“John is in the map”。由于Map中不存在“Mike”键,所以第二个if语句输出“Mike is not in the map”。

综上所述,Map中判断一个键是否存在的方法有两种:使用count()函数和使用find()函数。使用哪种方法取决于用户的具体需求和编程习惯。但无论哪种方法,都可以实现判断Map中键的存在性操作。

  
  
下一篇: 整除的数的和

评论区

{{item['qq_nickname']}}
()
回复
回复