Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน map find () ใน C ++ STL


ในบทความนี้เราจะพูดถึงการทำงาน ไวยากรณ์และตัวอย่างของฟังก์ชัน map::find() ใน C++ STL

แผนที่ใน C++ STL คืออะไร

แผนที่เป็นคอนเทนเนอร์ที่เชื่อมโยงกัน ซึ่งอำนวยความสะดวกในการจัดเก็บองค์ประกอบที่เกิดขึ้นจากการรวมกันของค่าคีย์และค่าที่แมปในลำดับเฉพาะ ในคอนเทนเนอร์แผนที่ ข้อมูลจะถูกจัดเรียงภายในเสมอโดยใช้คีย์ที่เกี่ยวข้อง ค่าในคอนเทนเนอร์แผนที่สามารถเข้าถึงได้โดยคีย์เฉพาะของมัน

map::find() คืออะไร

map::find( ) เป็นฟังก์ชันที่อยู่ภายใต้ไฟล์ส่วนหัว ฟังก์ชันนี้ส่งคืนตัววนซ้ำซึ่งชี้ไปยังองค์ประกอบของคีย์ที่กำหนดซึ่งเราต้องการค้นหา

ไวยากรณ์

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;
   }
   //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