在本文中,我们将讨论C ++ STL中map::find()函数的工作,语法和示例。
映射是关联容器,它有助于按特定顺序存储键值和映射值的组合所形成的元素。在映射容器中,数据始终在内部借助其关联的键进行排序。映射容器中的值通过其唯一键访问。
map::find()是<map>头文件下的函数。此函数返回一个迭代器,该迭代器指向要搜索的给定键的元素。
map_name.find(key_value k);
该功能接受以下
k:这是我们要从映射容器中搜索的键值
它返回一个指向与键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;
}
//在位置找到映射值
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