ภาพรวม
deque::cbegin() เป็น Member Function ของ std::deque (header <deque>) คืนค่า Const Iterator ชี้ไปยัง องค์ประกอบแรก ของ Deque
Syntax
const_iterator cbegin() const noexcept;
คุณสมบัติ
- ไม่รับพารามิเตอร์
- คืนค่า
const_iterator(Random Access Iterator) - ใช้ อ่านค่าได้อย่างเดียว ไม่สามารถแก้ไขข้อมูลผ่าน Iterator นี้ได้
- เวอร์ชัน Non-const คือ
begin()
ตัวอย่างโค้ด
#include <deque>
#include <iostream>
using namespace std;
int main() {
deque<int> dqe = {65, 2, 31, 5, 9};
cout << "First element of the deque is: ";
cout << *dqe.cbegin(); // แสดงค่า 65
// วนลูปอ่านค่าทั้งหมด
cout << "\nAll elements: ";
for (auto it = dqe.cbegin(); it != dqe.cend(); ++it) {
cout << *it << " ";
}
cout << endl;
return 0;
}
ผลลัพธ์
First element of the deque is: 65
All elements: 65 2 31 5 9
คำอธิบายเพิ่มเติม
cbegin()ย่อมาจาก Constant Begin- คู่คือ
cend()(ชี้ไปยังตำแหน่งหลังองค์ประกอบสุดท้าย) - ใช้ใน Range-based for loop ได้โดยอัตโนมัติ:
for (const auto& x : dqe) - Const Iterator ป้องกันการแก้ไขข้อมูลโดยไม่ตั้งใจ - Good Practice สำหรับ Read-only Access
ฟังก์ชัน Iterator คู่ของ Deque
| Non-const | Const | Reverse | Const Reverse |
|---|---|---|---|
begin() | cbegin() | rbegin() | crbegin() |
end() | cend() | rend() | crend() |