檢查鍵是否出現在 C++ map 或 unordered_map 中


在 C++ 中,地圖和無序地圖是雜湊表。它們使用一些鍵及其各自的鍵值。下面我們將瞭解如何檢查給定的鍵是否存在於雜湊表中。程式碼如下 −

示例

 線上演示版

#include<iostream>
#include<map>
using namespace std;
string isPresent(map<string, int> m, string key) {
   if (m.find(key) == m.end())
   return "Not Present";
   return "Present";
}
int main() {
   map<string, int> my_map;
   my_map["first"] = 4;
   my_map["second"] = 6;
   my_map["third"] = 6;
   string check1 = "fifth", check2 = "third";
   cout << check1 << ": " << isPresent(my_map, check1) << endl;
   cout << check2 << ": " << isPresent(my_map, check2);
}

輸出

fifth: Not Present
third: Present

更新日期: 2019 年 12 月 17 日

已檢視 370 次

開啟您的職業生涯

完成課程以獲得認證

開始
廣告