Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ฟังก์ชัน cbegin() และ cend() ของ list ใน C++ STL

บทนำ

งานนี้แสดงการทำงานของ list::cbegin() และ list::cend() ใน C++

ทั้งสองฟังก์ชันเป็นส่วนหนึ่งของ C++ STL ต้อง include <list>

list::cbegin()

คืนค่า Constant Iterator ชี้อิลิเมนต์แรก ใช้วนลูปได้แต่ไม่แก้ไขค่า (Read-only)

Syntax

List_Name.cbegin();

Return Value

Constant Iterator ชี้ Beginning ของลิสต์

list::cend()

คืนค่า Constant Iterator ชี้ Past-the-end (หลังอิลิเมนต์สุดท้าย) ใช้เป็นเงื่อนไขหยุดลูป Read-only

Syntax

List_Name.cend();

Return Value

Constant Iterator ชี้ Past-the-end ของลิสต์

ตัวอย่าง

Input: list<int> Lt = {4, 8, 9}
Output: 4

cbegin() ชี้ตัวแรก (4) พิมพ์ได้ 4

แนวทางในโปรแกรม

  • สร้าง list Ld ประเภท int กำหนดค่า
  • วนลูปพิมพ์ลิสต์
  • สร้าง iterator itr ในลูป รับค่าจาก cbegin() และ cend()
  • เริ่มจาก cbegin() จนกว่าจะถึง cend()
  • พิมพ์ *itr

อัลกอริทึม

Start
Step 1 → In main()
    Initialize list<int> Lt = {}
    Loop for auto itr = Lt.cbegin() and itr != Lt.cend() and itr++
    Print *itr
End
Stop

ตัวอย่างโค้ด

#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> Lt = { 4, 1, 7, 9, 6 };
    cout << "The elements of the list are : " << "\n";
    for (auto itr = Lt.cbegin(); itr != Lt.cend(); itr++)
        cout << *itr << " ";
    return 0;
}

ผลลัพธ์

4 1 7 9 6

คำอธิบายเพิ่มเติม

cbegin() และ cend() คืนค่า const_iterator ใช้เมื่อต้องการอ่านอย่างเดียว ไม่อนุญาตให้แก้ไขค่าผ่าน Iteratorเหล่านี้ เหมาะสำหรับฟังก์ชันที่รับ list แบบ const reference