#include <iostream>
#include <map>
using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;
int main(){
std::map<string, string> m1 = {{"h", "htop"},
{"k", "ktop"},
{"t", "ttop"},
{"r", "rtop"},
{"w", "wtop"},
{"p", "ptop"},};
string key = "h";
auto item = m1.find(key);
if (item != m1.end()) {
cout << "Key exists! - {" <<
item->first << ";" << item->second << "}\n";
} else {
cout << "Key does not exist!" << endl;
return EXIT_SUCCESS;
使用 contains
成员函数检查 C++ 映射中是否存在给定元素
如果用户需要确认具有给定值的一对是否存在于 map
对象中,可以使用成员函数 contains
。自 C++20 版本以来,该函数一直是 std::map
容器的一部分,因此你应该知道编译器版本才能运行以下代码片段。contains
函数获取对键的引用,如果找到,则返回 bool
值 true
。这个成员函数的时间复杂度也是对数的。
#include <iostream>
#include <map>
using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;
int main(){
std::map<string, string> m1 = {{"h", "htop"},
{"k", "ktop"},
{"t", "ttop"},
{"r", "rtop"},
{"w", "wtop"},
{"p", "ptop"},};
string key = "h";
if (m1.contains(key)) {
cout << "Key Exists!" << endl;
} else {
cout << "Key does not exist!" << endl;
return EXIT_SUCCESS;
或者,可以使用 cout
成员函数来检查具有给定键的元素对是否存在于 map
中。通常,cout
函数用于检索具有给定键的元素数量,但由于 std::map
仅存储唯一的键值,如果找到该元素,该过程将返回 1
。否则,返回零值以指示未找到元素。
#include <iostream>
#include <map>
using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;
int main(){
std::map<string, string> m1 = {{"h", "htop"},
{"k", "ktop"},
{"t", "ttop"},
{"r", "rtop"},
{"w", "wtop"},
{"p", "ptop"},};
string key = "h";
if (m1.count(key)) {
cout << "Key Exists!" << endl;
} else {
cout << "Key does not exist!" << endl;
return EXIT_SUCCESS;
Key Exists!
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn