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

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


งานนี้เป็นการแสดงฟังก์ชันการทำงานของ list::begin() และ list::end() ใน C++ STL

List ใน STL คืออะไร

List เป็นโครงสร้างข้อมูลที่อนุญาตให้แทรกและลบได้ในเวลาคงที่ที่ตำแหน่งใดก็ตามในลำดับ List ถูกนำไปใช้เป็น doubly linked lists List อนุญาตการจัดสรรหน่วยความจำแบบไม่ต่อเนื่อง List ทำงานการแทรก ดึง และย้ายองค์ประกอบได้ดีกว่า array, vector และ deque ใน List การเข้าถึงองค์ประกอบโดยตรงช้า และ list คล้ายกับ forward_list แต่วัตถุ forward_list เป็น singly linked lists และสามารถวนรอบได้เฉพาะไปข้างหน้า

begin() คืออะไร

ฟังก์ชัน list::begin() ใช้คืนค่า iterator ที่ชี้ไปยังองค์ประกอบแรกของ list

ไวยากรณ์

list_name.begin()

end() คืออะไร?

ฟังก์ชัน list::end() ใช้คืนค่า iterator ที่ชี้ไปยังตำแหน่งหลังองค์ประกอบสุดท้ายของ list

ไวยากรณ์

list_name.end()

ตัวอย่าง

เอาต์พุต - List - 10 11 12 13 14

เอาต์พุต - List - 66 67 68 69 70

แนวทางการทำงาน

  • เริ่มต้น list ก่อน
  • กำหนด begin() และ end()

ด้วยแนวทางด้านบน เราสามารถพิมพ์ list โดยใช้ฟังก์ชัน begin() และ end()

ตัวอย่าง

// C++ code to demonstrate the working of begin() and end() function in STL
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<int> lst = { 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
    // print the list
    cout << "Elements in List: ";
    for(auto x = lst.begin(); x != lst.end(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Elements in List: 11 12 13 14 15 16 17 18 19 20

ตัวอย่างที่ 2

// C++ code to demonstrate the working of list begin() and end() function in STL
#include <iostream>
#include <list>
using namespace std;

int main() {
    list<char> lst = { 'D', 'E', 'S', 'I', 'G', 'N' };
    // print the list
    cout << "Elements in List: ";
    for(auto x = lst.begin(); x != lst.end(); ++x)
        cout << *x << " ";
    return 0;
}

เอาต์พุต

Elements in List: D E S I G N