ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::lower_bound() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::lower_bound() คืออะไร?
map::lower_bound(k) คืน Iterator ชี้ไปที่ Element แรกที่มี Key
Syntax
map_name.lower_bound(key& k);
Parameters
k − Key ที่ต้องการค้นหา Lower Bound
Return Value
Iterator ชี้ Element ที่ Key ≥ k แรกที่พบ ถ้าไม่มี คืน end()
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> TP_Map;
TP_Map.insert({5, 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.rbegin(); i != TP_Map.rend(); i++)
cout << i->first << "\t" << i->second << endl;
auto it = TP_Map.lower_bound(2);
cout << "The lower bound of key 2 is " << it->first << " : " << it->second << endl;
auto it2 = TP_Map.lower_bound(3);
cout << "The lower bound of key 3 is " << it2->first << " : " << it2->second << endl;
return 0;
}
ผลลัพธ์
TP Map is: MAP_KEY MAP_ELEMENT 5 50 4 70 2 30 1 10 The lower bound of key 2 is 2 : 30 The lower bound of key 3 is 4 : 70
คำอธิบาย
- Key 2: มีอยู่ใน Map → Lower bound คือ Key 2 เอง (เพราะ ≥ 2)
- Key 3: ไม่มีใน Map → Lower bound คือ Key 4 (Key ถัดไปที่ ≥ 3)
ความแตกต่างกับ upper_bound()
lower_bound(k)= Key แรกที่ ≥ k (รวม k)upper_bound(k)= Key แรกที่ > k (ไม่รวม k)