ในบทความนี้ เราจะอธิบายการทำงาน ไวยากรณ์ และตัวอย่างของฟังก์ชัน map::crbegin() และ map::crend() ใน C++ STL
Map ใน C++ STL คืออะไร?
Map เป็น Associative Container ที่เก็บข้อมูลเป็นคู่ Key-Value จัดเรียงตาม Key อัตโนมัติ Key ต้องไม่ซ้ำกัน
map::crbegin() คืออะไร?
map::crbegin() ย่อมาจาก Constant Reverse Begin คืน Constant Reverse Iterator ชี้ Element สุดท้าย ไม่สามารถแก้ไขค่าได้ ใช้สำหรับอ่านอย่างเดียว
Syntax
map_name.crbegin();
Return Value
Constant Reverse Iterator ชี้ Element สุดท้าย
map::crend() คืออะไร?
map::crend() ย่อมาจาก Constant Reverse End คืน Constant Reverse Iterator ชี้ Past-the-beginning ใช้เป็นเงื่อนไขหยุดใน Reverse Iteration แบบ Read-only
Syntax
map_name.crend();
Return Value
Constant Reverse Iterator ชี้ Past-the-beginning
ตัวอย่าง
#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});
// ใช้ crbegin() ดึง Element สุดท้าย (Read-only)
auto temp = TP_Map.crbegin();
cout << "First element (const reverse): " << temp->first << " -> " << temp->second;
cout << "\nTP Map is (Const Reverse Order): \nMAP_KEY\tMAP_ELEMENT\n";
for (auto i = TP_Map.crbegin(); i != TP_Map.crend(); i++)
cout << i->first << "\t" << i->second << endl;
return 0;
}
ผลลัพธ์
First element (const reverse): 4 -> 70 TP Map is (Const Reverse Order): MAP_KEY MAP_ELEMENT 4 70 3 50 2 30 1 10
ความแตกต่างระหว่าง rbegin/rend และ crbegin/crend
| ฟังก์ชัน | Iterator Type | สามารถแก้ไขค่าได้? |
|---|---|---|
| rbegin()/rend() | Reverse Iterator | ได้ |
| crbegin()/crend() | Constant Reverse Iterator | ไม่ได้ (Read-only) |