Linux 拨号vps windows公众号手机端

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

lewis 8年前 (2017-05-24) 阅读数 8 #程序编程
文章标签 c++

在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中。

版权声明

本文仅代表作者观点,不代表米安网络立场。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门