檢查鍵是否出現在 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
廣告