检查 C++ 映射或 unordered_map 中是否存在某个键
c++server side programmingprogramming
在 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