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

ฟังก์ชัน list::end() ใน C++ STL

ฟังก์ชัน list::end() ใน C++ STL

list::end() คืออะไร?

คืน iterator ชี้ไปตำแหน่ง หลังองค์ประกอบสุดท้าย (past-the-end) ไม่ชี้องค์ประกอบจริง ใช้ร่วมกับ begin() เพื่อให้ range ของ container

Syntax

list_container.end();

พารามิเตอร์

ไม่มี

คืนค่า

Iterator ชี้ past-the-end

ตัวอย่าง 1: วนลูปด้วย begin()/end()

#include <bits/stdc++.h>
using namespace std;

int main() {
    list<int> myList;
    myList.push_back(67);
    myList.push_back(12);
    myList.push_back(32);
    myList.push_back(780);
    myList.push_back(78);
    
    cout << "elements in the list are:\n";
    for (auto it = myList.begin(); it != myList.end(); it++)
        cout << *it << " ";
    return 0;
}

Output: elements in the list are: 67 12 32 780 78

ตัวอย่าง 2: ใช้ Constructor ที่รับ Iterator Range

#include <iostream>
#include <list>

int main() {
    int values[] = {67, 12, 32, 780, 78};
    std::list<int> myList(values, values + 5);  // [begin, end)
    
    std::cout << "elements in the list are:\n";
    for (std::list<int>::iterator it = myList.begin(); it != myList.end(); ++it)
        std::cout << ' ' << *it;
    return 0;
}

Output: elements in the list are: 67 12 32 780 78

ข้อสังเกตสำคัญ

  • end() ไม่สามารถ dereference ได้ (*end() → undefined behavior)
  • ใช้เป็น sentinel ใน loops: for (it = begin(); it != end(); ++it)
  • มี cbegin()/cend() สำหรับ const iterators (C++11)
  • มี rbegin()/rend() สำหรับ reverse iteration

Complexity

  • O(1) - แค่คืน iterator object
  • Noexcept