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

forward_list::cend() ใน C++ STL

บทนำ

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

forward_list เก็บลิงก์เฉพาะอิลิเมนต์ถัดไป วนลูปได้เฉพาะทิศทางหน้า

forward_list::cend() เป็นส่วนหนึ่งของ C++ STL ใช้เพื่อรับอิลิเมนต์สุดท้ายของลิสต์

ต้อง include <forward_list>

Syntax

Forward_List_Name.cend();

Parameters

ไม่รับพารามิเตอร์

Return Value

คืนค่า Constant Iterator ที่ชี้อิลิเมนต์สุดท้ายของ forward_list

ตัวอย่าง

Input: forward_list<int> Lt = {8, 9, 7}; cout << *Lt.cend();
Output: 7

คำอธิบาย - สร้างลิสต์ {8, 9, 7} เรียก cend() ชี้ตัวสุดท้าย พิมพ์ได้ 7

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

  • สร้าง 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 = { 9, 55, 6, 100 };
    // พิมพ์องค์ประกอบของลิสต์
    cout << "The elements of the list are : " << "\n";
    for (auto itr = Lt.cbegin(); itr != Lt.cend(); itr++)
        cout << *itr << " ";
    return 0;
}

ผลลัพธ์

9 55 6 100

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

cend() คืนค่า iterator ชี้ "หลัง" อิลิเมนต์สุดท้าย (Past-the-end) ใช้เป็นเงื่อนไขหยุดลูป ไม่สามารถ dereference (*itr) ได้เมื่อ itr == cend()