Deque คืออะไร?
Deque (Double Ended Queue) เป็นคอนเทนเนอร์แบบลำดับที่ให้ฟังก์ชันการขยายและหดตัวได้ที่ ทั้งสองปลาย** แตกต่างจาก queue ปกติที่แทรกได้แค่ท้าย (END) และลบได้แค่หน้า (FRONT) ใน deque สามารถแทรกและลบได้ทั้งสองด้าน
deque::crend() คืออะไร?
deque::crend() ส่งคืน const_reverse_iterator ที่ชี้ไปยังตำแหน่ง ก่อนหน้าองค์ประกอบแรก (reverse end) ของ deque ซึ่งถือเป็นปลายท้ายในมุมมองแบบกลับลำดับ (reverse) นั่นคือ ตำแหน่งที่อยู่ "ก่อน" องค์ประกอบแรกเมื่อมองจากท้ายไปหาหน้า
ไวยากรณ์ (Syntax)
deque_name.crend()
ค่าที่ส่งคืน (Return Value)
ส่งคืน const_reverse_iterator ของ deque
ตัวอย่างการใช้งาน crend() เพื่อพิมพ์ deque แบบกลับลำดับ
// C++ code to demonstrate the working of deque crend() function
#include <deque>
#include <iostream>
using namespace std;
int main() {
// ประกาศ deque
deque<int> dq = {5, 4, 3, 2, 1};
// พิมพ์ deque ปกติ
cout << "Deque: ";
for (auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
// พิมพ์ deque แบบกลับลำดับด้วย crend() และ crbegin()
cout << "\nDeque ในลำดับกลับ: ";
for (auto x = dq.crbegin(); x != dq.crend(); ++x)
cout << *x << " ";
return 0;
}
ผลลัพธ์ (Output)
Deque: 5 4 3 2 1 Deque ในลำดับกลับ: 1 2 3 4 5
ตัวอย่างที่ 2: deque ของตัวอักษร
#include <deque>
#include <iostream>
using namespace std;
int main() {
deque<char> dq = {'L', 'A', 'P', 'T', 'O', 'P'};
cout << "Deque: ";
for (auto x = dq.begin(); x != dq.end(); ++x)
cout << *x << " ";
cout << "\nDeque ในลำดับกลับ: ";
for (auto x = dq.crbegin(); x != dq.crend(); ++x)
cout << *x << " ";
return 0;
}
ผลลัพธ์ (Output)
Deque: L A P T O P Deque ในลำดับกลับ: P O T P A L
แก้ไขจากโค้ดต้นฉบับ: โค้ดต้นฉบับใช้ deque.crend() - 1 และ x >= deque.begin() ซึ่ง ไม่ถูกต้อง** เพราะ reverse_iterator ไม่สามารถลบด้วยจำนวนเต็มได้โดยตรง และไม่สามารถเปรียบเทียบกับ forward iterator ได้ ควรใช้ crbegin() และ crend() คู่กันในลูป for แบบปกติ
คู่ iterator แบบกลับลำดับ (Reverse iterators):
rbegin()- ชี้ไปยังองค์ประกอบสุดท้าย (reverse begin)rend()- ชี้ไปยังก่อนองค์ประกอบแรก (reverse end)crbegin()- const version ของ rbegin()crend()- const version ของ rend()