ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::key_comp() ใน C++ STL
แผนที่ใน C++ STL คืออะไร
แผนที่เป็นคอนเทนเนอร์ที่เชื่อมโยงกัน ซึ่งอำนวยความสะดวกในการจัดเก็บองค์ประกอบที่เกิดขึ้นจากการรวมกันของค่าคีย์และค่าที่แมปในลำดับเฉพาะ ในคอนเทนเนอร์แผนที่ ข้อมูลจะถูกจัดเรียงภายในเสมอโดยใช้คีย์ที่เกี่ยวข้อง ค่าในคอนเทนเนอร์แผนที่สามารถเข้าถึงได้โดยคีย์เฉพาะของมัน
map::key_comp() คืออะไร
map::key_comp( ) เป็นฟังก์ชันที่อยู่ภายใต้ไฟล์ส่วนหัว
ไวยากรณ์
Key_compare.key_comp();
พารามิเตอร์
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
คืนค่า
ส่งกลับวัตถุเปรียบเทียบ
ตัวอย่าง
อินพุต
map<char, int> newmap; map<char, int> :: key_compare cmp = newmap.key_comp(); newmap[‘a’] = 1; newmap[‘b’] = 2; newmap[‘c’] = 3;
ผลลัพธ์
a = 1 b = 2 c = 3
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, char> TP;
map<int, char>::key_compare cmp = TP.key_comp();
// Inserting 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;
map<int, char>::iterator i = TP.begin();
do {
cout << i->first << " : " << i->second<<'\n';
} while (cmp((*i++).first, val));
return 0;
} ผลลัพธ์
Elements in the map are: 0 : a 1 : b 2 : c 3 : d
ตัวอย่าง
#include <bits/stdc++.h>
using namespace std;
int main() {
map<char, int> TP;
map<char, int>::key_compare cmp = TP.key_comp();
// Inserting elements
TP['a'] = 0;
TP['b'] = 1;
TP['c'] = 3;
TP['d'] = 2;
cout<<"Elements in the map are : \n";
char val = TP.rbegin()->first;
map<char, int>::iterator i = TP.begin();
do {
cout << i->first << " : " << i->second<<'\n';
} while (cmp((*i++).first, val));
return 0;
} ผลลัพธ์
Elements in the map are: a : 0 b : 1 c : 3 d : 2