บทนำ
งานนี้แสดงการทำงานของ forward_list::cbegin() ใน C++
forward_list เก็บลิงก์เฉพาะอิลิเมนต์ถัดไป วนลูปได้เฉพาะทิศทางหน้า
forward_list::cbegin() เป็นส่วนหนึ่งของ C++ STL ใช้เพื่อรับอิลิเมนต์แรกของลิสต์
ต้อง include <forward_list>
Syntax
Forward_List_Name.cbegin();
Parameters
ไม่รับพารามิเตอร์
Return Value
คืนค่า Constant Iterator ที่ชี้อิลิเมนต์แรกของ forward_list
ตัวอย่าง
Input: 11, 4, 99 Output: 11
คำอธิบาย - สร้าง forward list {11, 4, 99} เรียก cbegin() ชี้ตัวแรก พิมพ์ได้ 11
แนวทางในโปรแกรม
- สร้าง forward_list Lt ประเภท int กำหนดค่า
- วนลูปพิมพ์ลิสต์
- สร้าง iterator itr ในลูป รับค่าจาก cbegin() และ cend()
- เริ่มจาก cbegin() จนกว่าจะถึง cend()
- พิมพ์ *itr
อัลกอริทึม
Start
Step 1 → In main()
Initialize forward_list<int> Lt = {}
Loop for auto itr = Lt.cbegin() and itr != Lt.cend() and itr++
Print *itr
End
Stop
ตัวอย่างโค้ด
#include <iostream>
#include <forward_list>
using namespace std;
int main() {
forward_list<int> Lt = { 67, 88, 99, 10 };
// พิมพ์องค์ประกอบของลิสต์
cout << "The elements of the list are : " << "\n";
for (auto itr = Lt.cbegin(); itr != Lt.cend(); itr++)
cout << *itr << " ";
return 0;
}
ผลลัพธ์
67 88 99 10
คำอธิบายเพิ่มเติม
cbegin() คืนค่า const_iterator ใช้สำหรับอ่านอย่างเดียว (Read-only) ไม่สามารถแก้ไขค่าผ่าน iterator นี้ได้ เหมาะสำหรับการวนลูปอ่านค่า