温馨提示×

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

c++
小亿
103
2023-12-22 22:43:17
栏目: 编程语言

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

0