溫馨提示×

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

c++
小億
552
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女