21xrx.com
2024-09-19 09:41:08 Thursday
登录
文章检索 我的文章 写文章
如何判断C++的map中是否存在指定的key?
2023-07-04 18:23:02 深夜i     --     --
C++ map 判断 存在 key

C++的map是一种关联容器,它将每个key映射到其对应的value。在开发中,我们经常需要判断某个key是否存在于map中。本文将介绍两种判断C++的map中是否存在指定的key的方法。

方法一:使用count函数

C++的map内置了一个count函数,它可以用于获取某个key在map中出现的次数,如果该key不存在,则返回0。因此,我们可以使用count函数来判断某个key是否存在于map中。

示例代码如下:


#include<iostream>

#include<map>

using namespace std;

int main()

{

  map<int,string> testMap;

  testMap[1]="Tom";

  testMap[2]="John";

  testMap[3]="Lily";

  int key=2;

  if(testMap.count(key)>0)

  {

    cout<<"Key "<<key<<" exists in map.\n";

  }

  else

  {

    cout<<"Key "<<key<<" does not exist in map.\n";

  }

  return 0;

}

输出结果为:“Key 2 exists in map.”。在该示例中,我们可以看到count函数返回的值大于0,即key存在于map中。

方法二:使用find函数

C++的map内置了一个find函数,它可以在map中查找某个key,并返回指向该key的迭代器。如果该key不存在,则返回map的end迭代器。因此,我们可以使用find函数来判断某个key是否存在于map中。

示例代码如下:


#include<iostream>

#include<map>

using namespace std;

int main()

{

  map<int,string> testMap;

  testMap[1]="Tom";

  testMap[3]="Lily";

  int key=2;

  if(testMap.find(key)!=testMap.end())

  {

    cout<<"Key "<<key<<" exists in map.\n";

  }

  else

  {

    cout<<"Key "<<key<<" does not exist in map.\n";

  }

  return 0;

}

输出结果为:“Key 2 does not exist in map.”。在该示例中,我们可以看到find函数返回的迭代器等于end迭代器,即key不存在于map中。

在使用find函数时,需要注意迭代器的类型。对于map ,其迭代器类型为map ::iterator,我们可以使用auto关键字来简化迭代器类型的声明,如下所示:


auto findResult=testMap.find(key);

if(findResult!=testMap.end())

  //key存在于map中

通过使用count函数或find函数,我们可以方便快捷地判断C++的map中是否存在指定的key。在日常开发中,我们应根据具体情况灵活选择合适的判断方法。

  
  

评论区

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