ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::find() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::find() คืออะไร?
map::find(k) ค้นหา Element ที่มี Key เท่ากับ k คืน Iterator ชี้ไป Element นั้น ถ้าไม่พบ คืน end()
ซับซ้อน: O(log n) เร็วกว่าการ Iterate ทั้ง Map
Syntax
map_name.find(key_value k);
Parameters
k − Key ที่ต้องการค้นหา
Return Value
Iterator ชี้ Element ที่ Key = k ถ้าไม่พบ คืน end()
ตัวอย่าง 1: ค้นหา Key ที่มีอยู่
#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 : \nMAP_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 var2 = TP_Map.find(2);
cout << "\nFound element at position " << var2->first << " is : " << var2->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
ตัวอย่าง 2: ใช้ find() เป็นจุดเริ่มต้น Iterate
#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 from key 2: \nMAP_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 from key 2: MAP_KEY MAP_ELEMENT 2 30 3 50 4 70
สรุป
find()ค้นหา Key แบบ Binary Search O(log n)- คืน Iterator → ตรวจสอบด้วย
!= end()ก่อนใช้งาน - ใช้เริ่มต้น Loop จาก Key ใด Key หนึ่งได้