Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน multimap::crbegin() และ multimap::crend() ใน C++ STL

Multimap ใน C++ STL คืออะไร?

Multimap เป็น associative container ที่คล้ายกับ map แต่อนุญาตให้มีหลายค่าผูกกับคีย์เดียวกันได้ ข้อมูลจัดเรียงอัตโนมัติตามคีย์

ฟังก์ชัน multimap::crbegin() คืออะไร?

ฟังก์ชัน multimap::crbegin() (constant reverse begin) ประกาศอยู่ใน header <map> คืนค่า constant reverse iterator ชี้ไปยังองค์ประกอบสุดท้ายของ multimap container ใช้สำหรับ遍历แบบย้อนกลับ (reverse traversal) แบบ read-only

รูปแบบไวยากรณ์ (Syntax)

multiMap_name.crbegin();

พารามิเตอร์

ไม่รับพารามิเตอร์

ค่าที่ส่งคืน

คืนค่า const_reverse_iterator ชี้ไปยังองค์ประกอบสุดท้าย

ฟังก์ชัน multimap::crend() คืออะไร?

ฟังก์ชัน multimap::crend() (constant reverse end) ประกาศอยู่ใน header <map> คืนค่า constant reverse iterator ชี้ไปยังตำแหน่ง ก่อนองค์ประกอบแรก (preceding the first element) ใช้เป็นจุดสิ้นสุดในการ遍历แบบย้อนกลับ

รูปแบบไวยากรณ์ (Syntax)

newmultimap.crend();

พารามิเตอร์

ไม่รับพารามิเตอร์

ค่าที่ส่งคืน

คืนค่า const_reverse_iterator ชี้ไปยังตำแหน่งก่อนองค์ประกอบแรก

ตัวอย่างการใช้งาน

#include <bits/stdc++.h>
using namespace std;

int main() {
    // สร้าง container
    multimap<int, int> mul;
    
    // แทรกข้อมูลด้วย emplace_hint
    mul.emplace_hint(mul.begin(), 1, 10);
    mul.emplace_hint(mul.begin(), 2, 20);
    mul.emplace_hint(mul.begin(), 2, 30);
    mul.emplace_hint(mul.begin(), 1, 40);
    mul.emplace_hint(mul.begin(), 1, 50);
    mul.emplace_hint(mul.begin(), 5, 60);
    
    auto it = mul.crbegin();
    cout << "Last element using crbegin() is: {" << it->first << ", " << it->second << "}\n";
    
    cout << "\nElements in multimap is: \n";
    cout << "KEY\tELEMENT\n";
    for (auto i = mul.crbegin(); i != mul.crend(); i++) {
        cout << i->first << "\t" << i->second << endl;
    }
    
    return 0;
}

ผลลัพธ์

Last element using crbegin() is: {5, 60}
Elements in multimap is:
KEY	ELEMENT
5	60
2	20
2	30
1	10
1	40
1	50

สรุป Iterator ประเภทต่างๆ ใน Multimap

ฟังก์ชันประเภททิศทางจุดเริ่มต้น
begin() / end()iteratorForwardFirst / Past-last
cbegin() / cend()const_iteratorForwardFirst / Past-last
rbegin() / rend()reverse_iteratorReverseLast / Before-first
crbegin() / crend()const_reverse_iteratorReverseLast / Before-first

สรุป

crbegin() และ crend() เป็น constant reverse iterator version ใช้สำหรับ reverse traversal แบบ read-only ของ multimap เหมาะสำหรับการวนลูปย้อนกลับเมื่อไม่ต้องการแก้ไขข้อมูล