ในบทความนี้ เราจะพูดถึงการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน multimap::key_comp() ใน C++ STL
มัลติแมปใน C++ STL คืออะไร
Multimaps เป็นคอนเทนเนอร์ที่เชื่อมโยงกัน ซึ่งคล้ายกับคอนเทนเนอร์แผนที่ นอกจากนี้ยังอำนวยความสะดวกในการจัดเก็บองค์ประกอบที่เกิดจากการรวมกันของคีย์-ค่าและค่าที่แมปในลำดับเฉพาะ ในคอนเทนเนอร์แบบหลายแผนที่ อาจมีองค์ประกอบหลายรายการที่เชื่อมโยงกับคีย์เดียวกัน ข้อมูลจะถูกจัดเรียงภายในเสมอโดยใช้คีย์ที่เกี่ยวข้อง
มัลติแมป::key_comp() คืออะไร
multimap::key_comp( ) เป็นฟังก์ชันที่อยู่ภายใต้ไฟล์ส่วนหัว
ไวยากรณ์
Key_compare.key_comp();
พารามิเตอร์
ฟังก์ชันนี้ไม่รับพารามิเตอร์ใดๆ
คืนค่า
ส่งกลับวัตถุเปรียบเทียบ
ป้อนข้อมูล
multimap<char, int> newmap; multimap<char, int> :: key_compare cmp = newmap.key_comp(); newmap.insert(make_pair(‘A’, 1)); newmap.insert(make_pair(‘B’, 2)); newmap.insert(make_pair(‘C’, 3));
ผลผลิต
A= 1 B= 2 C= 3
ตัวอย่าง
#include <iostream>
#include <map<
using namespace stgd;
int main(){
multimap<int, char> mul;
multimap<int, char>::key_compare cmp = mul.key_comp();
//inserting elements at given key
mul.insert(make_pair(0, 'A'));
mul.insert(make_pair(1, 'B'));
mul.insert(make_pair(2, 'C'));
mul.insert(make_pair(3, 'D'));
int a = mul.rbegin()->first;
multimap<int, char>::iterator it = mul.begin();
cout<<"Elements at given key is : "<<'\n';
do {
cout << it->first << " = " << it->second << '\n';
}
while (cmp((*it++).first, a));
return 0;
} ผลลัพธ์
หากเราเรียกใช้โค้ดด้านบน มันจะสร้างผลลัพธ์ต่อไปนี้ -
Elements at given key is : 0 = A 1 = B 2 = C 3 = D