map find() C++ STL 函式
在本文中,我們將討論 C++ STL 中 map::find() 函式的工作原理、語法和示例。
什麼是 C++ STL 中的 Map?
Map 是關聯容器,有助於按照特定順序儲存由鍵值和對映值組合而成的元素。在 map 容器中,資料始終在關聯鍵的幫助下在內部進行排序。可以透過其唯一鍵訪問 map 容器中的值。
什麼是 map::find()?
map::find( ) 是一個包含在 <map> 標頭檔案下的函式。該函式返回指向元素的迭代器,該元素屬於我們想要搜尋的給定鍵。
語法
map_name.find(key_value k);
引數
此函式接受以下引數
引數
k: 這是我們要從 map 容器中搜索的鍵值
返回值
它返回指向與鍵 k 關聯的元素的迭代器。
示例
輸入
map<char, int> newmap; newmap[‘a’] = 1; newmap[‘b’] = 2; newmap.find(b);
輸出
2
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
cout<<"TP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.begin(); i!= TP_Map.end(); i++) {
cout << i->first << "\t" << i->second << endl;
}
//to find the map values at position
auto var = TP_Map.find(1);
cout<<"Found element at position "<<var->first<<" is : "<<var->second;
auto var_1 = TP_Map.find(2);
cout<<"\nFound element at position "<<var_1->first<<" is : "<<var_1->second;
return 0;
}輸出
TP Map is: MAP_KEY MAP_ELEMENT 1 10 2 30 3 50 4 70 Found element at position 1 is : 10 Found element at position 2 is : 30
示例
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({3, 50});
TP_Map.insert({2, 30});
TP_Map.insert({1, 10});
TP_Map.insert({4, 70});
cout<<"TP Map is : \n";
cout << "MAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.find(2); i!= TP_Map.end(); i++) {
cout << i->first << "\t" << i->second << endl;
}
return 0;
}輸出
TP Map is: MAP_KEY MAP_ELEMENT 2 30 3 50 4 70
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP