บทนำ
งานนี้แสดงการทำงานของ list::crbegin() และ list::crend() ใน C++
ทั้งสองฟังก์ชันเป็นส่วนหนึ่งของ C++ STL ต้อง include <list>
list::crbegin()
คืนค่า Constant Iterator ชี้อิลิเมนต์สุดท้าย (Reverse Beginning) ใช้สำหรับ Backtracking แต่ไม่สามารถเปลี่ยนค่าได้ (Read-only)
Syntax
List_Name.crbegin()
Parameters
ไม่รับพารามิเตอร์
Return Value
Constant Reverse Iterator ชี้ Reverse Beginning (คือ End ของลิสต์)
list::crend()
คืนค่า Constant Iterator ชี้ Reverse End (คือ Beginning ของลิสต์) ใช้ Backtracking Read-only
Syntax
List_Name.crend()
Parameters
ไม่รับพารามิเตอร์
Return Value
Constant Reverse Iterator ชี้ Reverse Beginning (คือ Beginning ของลิสต์)
ตัวอย่าง
Input: list<int> Lt = {99, 34, 55}
Output: The last element is 55
crbegin() ชี้ตัวสุดท้าย (55) พิมพ์ได้ 55
แนวทางในโปรแกรม
- สร้าง list Ld ประเภท int กำหนดค่า
- วนลูปถอยหลัง (Reverse)
- สร้าง iterator itr ในลูป รับค่าจาก crend() และ crbegin()
- เริ่มจาก crend() (Beginning) จนถึง crbegin() (End)
- พิมพ์ *itr
อัลกอริทึม
Start
Step 1 → In main()
Initialize list<int> Lt = {}
Loop for auto itr = Lt.crend() and itr != Lt.crbegin() and itr++
Print *itr
End
Stop
ตัวอย่างโค้ด
#include <iostream>
#include <list>
using namespace std;
int main() {
list<int> Lt = { 33, 44, 55, 66 };
cout << "The elements of the list are : " << "\n";
for (auto itr = Lt.crend(); itr != Lt.crbegin(); itr++)
cout << *itr << " ";
return 0;
}
ผลลัพธ์
The elements of the list are : 66 55 44 33
หมายเหตุ
โค้ดต้นฉบับ Output แสดง "4" ซึ่งไม่ถูกต้อง โค้ดข้างบนแก้ไขให้ถูกต้อง: ใช้ crend() เริ่มต้น (ชี้ Beginning) และ crbegin() เป็นเงื่อนไขหยุด (ชี้ End) การ ++ บน reverse iterator จะย้อนกลับ
crbegin() = reverse begin (ชี้ last element), crend() = reverse end (ชี้ before first)