在 C++ 中檢查 map 中是否存在某個鍵值
-
使用
std::map::find函式檢查 C++ map 中是否存在某個鍵 -
使用
std::map::count函式檢查 C++ map 中是否存在某個鍵值 -
使用
std::map::contains函式檢查 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::cin;
using std::cout;
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::cin;
using std::cout;
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::cin;
using std::cout;
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!
Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
作者: Jinku Hu
