溫馨提示×

如何使用c++ map.count檢測鍵

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