检查键是否存在于C ++映射或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