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

ฟังก์ชัน map::rbegin() ใน C++ STL


ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::rbegin() ใน C++ STL

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

Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน

map::rbegin() คืออะไร?

map::rbegin() ย่อมาจาก Reverse Begin คืน Iterator ชี้ไปที่ Element สุดท้ายของ Map (Key ใหญ่ที่สุด) ใช้เริ่มต้นการ Iterate แบบ Reverse

Syntax

map_name.rbegin();

Parameters

ไม่มีพารามิเตอร์

Return Value

Reverse Iterator ชี้ Element สุดท้าย

ตัวอย่าง

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

int main() {
    map<int, int> TP_Map;
    TP_Map.insert({3, 50});
    TP_Map.insert({2, 30});
    TP_Map.insert({1, 10});
    TP_Map.insert({4, 70});
    
    // ใช้ rbegin() ดึง Element สุดท้าย
    auto temp = TP_Map.rbegin();
    cout << "First element (reverse): " << temp->first << " -> " << temp->second;
    
    cout << "\nTP Map is (Reverse Order): \nMAP_KEY\tMAP_ELEMENT\n";
    for (auto i = TP_Map.rbegin(); i != TP_Map.rend(); i++)
        cout << i->first << "\t" << i->second << endl;
    
    return 0;
}

ผลลัพธ์

First element (reverse): 4 -> 70
TP Map is (Reverse Order):
MAP_KEY     MAP_ELEMENT
4           70
3           50
2           30
1           10

สรุป

  • rbegin() = เริ่มต้น Reverse Iteration (Element สุดท้าย)
  • rend() = จบ Reverse Iteration (Past-the-beginning)
  • ใช้คู่กันเพื่อ Iterate Map จากท้ายไปหัว