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

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


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

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

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

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

map::rend() ย่อมาจาก Reverse End คืน Iterator ชี้ไปที่ตำแหน่ง ก่อน Element แรก (Reverse Past-the-beginning) ใช้เป็นเงื่อนไขหยุดเมื่อ Iterate แบบ Reverse

Syntax

map_name.rend();

Parameters

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

Return Value

Iterator ชี้ Past-the-beginning (ก่อน 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});
    
    cout << "TP 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;
}

ผลลัพธ์

TP Map is (Reverse Order):
MAP_KEY     MAP_ELEMENT
4           70
3           50
2           30
1           10

สรุป Iterator คู่สำหรับ Reverse Iteration

  • rbegin() = เริ่มต้นแบบ Reverse (ชี้ Element สุดท้าย)
  • rend() = จบแบบ Reverse (ชี้ Past-the-beginning)