温馨提示×

如何使用c++ map.count检测键

c++
小樊
86
2024-08-06 05:20:13
栏目: 编程语言

使用map.count()函数可以检测map中是否存在指定的键。它会返回一个整数值,表示指定键在map中出现的次数(要么是0,要么是1)。以下是一个简单的示例:

#include <iostream>
#include <map>

int main() {
    std::map<int, std::string> myMap;
    
    // 添加一些键值对
    myMap[1] = "apple";
    myMap[2] = "banana";
    myMap[3] = "cherry";
    
    // 检测键值1是否存在
    if (myMap.count(1) > 0) {
        std::cout << "Key 1 exists in the map" << std::endl;
    } else {
        std::cout << "Key 1 does not exist in the map" << std::endl;
    }
    
    // 检测键值4是否存在
    if (myMap.count(4) > 0) {
        std::cout << "Key 4 exists in the map" << std::endl;
    } else {
        std::cout << "Key 4 does not exist in the map" << std::endl;
    }
    
    return 0;
}

在这个例子中,我们创建了一个map,并使用myMap.count()函数检测了键值1和4是否存在。根据输出结果,我们可以确定这两个键值在map中的存在情况。

0