ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::key_comp() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::key_comp() คืออะไร?
map::key_comp() คืน Comparison Object (Key Compare) ที่ Map ใช้เรียงลำดับ Key โดย Default เป็น Less-than (operator<) คืน true ถ้า Key แรกน้อยกว่า Key ที่สอง (ควรอยู่ก่อน)
Syntax
map_name.key_comp();
Parameters
ไม่มีพารามิเตอร์
Return Value
Key Comparison Object
ตัวอย่าง 1: ใช้ Key Compare Iterate Map
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, char> TP;
auto cmp = TP.key_comp(); // เก็บ Comparison Object
// Insert Elements
TP[0] = 'a';
TP[1] = 'b';
TP[2] = 'c';
TP[3] = 'd';
cout << "Elements in the map are : \n";
int val = TP.rbegin()->first; // Key สุดท้าย (มากที่สุด)
auto it = TP.begin();
do {
cout << it->first << " : " << it->second << '\n';
} while (cmp((*it++).first, val)); // เปรียบเทียบ Key ปัจจุบันกับ Key สุดท้าย
return 0;
}
ผลลัพธ์
Elements in the map are: 0 : a 1 : b 2 : c 3 : d
ตัวอย่าง 2: Key เป็น Char
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char, int> TP;
auto cmp = TP.key_comp();
TP['a'] = 0;
TP['b'] = 1;
TP['c'] = 3;
TP['d'] = 2;
cout << "Elements in the map are : \n";
char val = TP.rbegin()->first;
auto it = TP.begin();
do {
cout << it->first << " : " << it->second << '\n';
} while (cmp((*it++).first, val));
return 0;
}
ผลลัพธ์
Elements in the map are: a : 0 b : 1 c : 3 d : 2
สรุป
key_comp()= เปรียบเทียบ Key (ใช้เรียงลำดับ Map)value_comp()= เปรียบเทียบ Value (น้อยใช้)- ทั้งคู่คืน Function Object ที่ทำงานเหมือน
operator<