c++中怎么用map查找key是否存在

   2025-02-13 8540
核心提示:在C++中,可以使用map的count()函数或者find()函数来查找key是否存在。使用count()函数:#include iostream#include mapint main

在C++中,可以使用mapcount()函数或者find()函数来查找key是否存在。

使用count()函数:

#include <iostream>#include <map>int main() {    std::map<int, std::string> myMap;    myMap[1] = "one";    myMap[2] = "two";    myMap[3] = "three";    if (myMap.count(2) > 0) {        std::cout << "Key 2 exists in the map" << std::endl;    }    else {        std::cout << "Key 2 does not exist in the map" << std::endl;    }    return 0;}

使用find()函数:

#include <iostream>#include <map>int main() {    std::map<int, std::string> myMap;    myMap[1] = "one";    myMap[2] = "two";    myMap[3] = "three";    if (myMap.find(2) != myMap.end()) {        std::cout << "Key 2 exists in the map" << std::endl;    }    else {        std::cout << "Key 2 does not exist in the map" << std::endl;    }    return 0;}

上述两种方法都可以判断key是否存在于map中。count()函数返回keymap中出现的次数,而find()函数返回指向key所在位置的迭代器。如果find()函数返回的迭代器等于map.end(),则表示key不存在于map中。

 
 
更多>同类维修知识
推荐图文
推荐维修知识
点击排行
网站首页  |  关于我们  |  联系方式  |  用户协议  |  隐私政策  |  网站留言