在 C++ 中检查 map 中是否存在某个键值
本文将介绍如何在 C++ 中检查 map 中是否存在某个键。
使用 std::map::find
函数检查 C++ map 中是否存在某个键
std::map
容器是一个键值对的关联数据结构,按顺序存储,每个元素都有一个唯一的键。另一方面,STL 还提供了一个名为 std::unordered_map
的同一个容器的未排序版本。这两个容器都支持下面描述的关键字搜索方法。
find
是 std::map
容器的内置函数之一,它采用对应键值的单个参数进行搜索。该函数返回具有给定键值的元素的迭代器,否则返回尾后迭代器。在以下示例中,我们初始化 std::pair<string, string>
类型的 map
,然后从传递给 find
函数的用户输入中获取键值。示例程序将肯定字符串输出到 cout
流。
#include <iostream>#include <map>using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;
int main(){
string key_to_find;
std::map<string, string> lang_map = {{"j", "Julia",},
{"p", "Python",},
{"m", "MATLAB",},
{"o", "Octave",},
{"s", "Scala",},
{"l", "Lua",}};
for (const auto & [key, value] : lang_map) {
cout << key << " : " << value << endl;
}
cout << "Enter the key to search for: ";
cin >> key_to_find;
if (lang_map.find(key_to_find) != lang_map.end()) {
cout << "Key Exists!" << endl;
}
return EXIT_SUCCESS;
}
输出:
j : Julia
l : Lua
m : MATLAB
o : Octave
p : Python
s : Scala
Enter the key to search for: l
Key Exists!
使用 std::map::count
函数检查 C++ map 中是否存在某个键值
或者,可以利用 std::map
容器的 count
内置函数来检查给定的键是否存在于 map 对象中。请注意,count
函数检索具有给定键值的元素的数量。如果没有找到键为 0
的元素,则返回值。因此,当给定的键存在于 map 对象中时,我们可以使用 count
函数调用作为 if
条件来输出确认字符串。
#include <iostream>#include <map>using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;
int main(){
string key_to_find;
std::map<string, string> lang_map = {{"j", "Julia",},
{"p", "Python",},
{"m", "MATLAB",},
{"o", "Octave",},
{"s", "Scala",},
{"l", "Lua",}};
cout << "Enter the key to search for: ";
cin >> key_to_find;
if (lang_map.count(key_to_find)) {
cout << "Key Exists!" << endl;
}
return EXIT_SUCCESS;
}
输出:
Enter the key to search for: l
Key Exists!
使用 std::map::contains
函数检查 C++ map 中是否存在某个键值
contains
是另一个内置函数,可用于查找键是否存在于 map
中。如果具有给定键的元素存在于对象中,则此函数返回一个布尔值。请注意,本文中列出的所有三个函数都具有对数复杂度。
#include <iostream>#include <map>using std::cout; using std::cin;
using std::endl; using std::map;
using std::string;
int main(){
string key_to_find;
std::map<string, string> lang_map = {{"j", "Julia",},
{"p", "Python",},
{"m", "MATLAB",},
{"o", "Octave",},
{"s", "Scala",},
{"l", "Lua",}};
cout << "Enter the key to search for: ";
cin >> key_to_find;
if (lang_map.contains(key_to_find)) {
cout << "Key Exists!" << endl;
}
return EXIT_SUCCESS;
}
输出:
Enter the key to search for: l
Key Exists!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。