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

การลบองค์ประกอบใน C++ STL list

ในบทช่วยสอนนี้ เราจะพูดถึงวิธีการลบองค์ประกอบใน C++ STL list โดยใช้ฟังก์ชัน pop_back() และ pop_front() เพื่อลบองค์ประกอบจากด้านหลังและด้านหน้าตามลำดับ

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

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

int main() {
    list<int> list1 = {10, 15, 20, 25, 30, 35};
    
    cout << "The original list is : ";
    for(auto i = list1.begin(); i != list1.end(); i++)
        cout << *i << " ";
    cout << endl;
    
    // ลบองค์ประกอบแรก
    list1.pop_front();
    cout << "The list after deleting first element using pop_front() : ";
    for(auto i = list1.begin(); i != list1.end(); i++)
        cout << *i << " ";
    cout << endl;
    
    // ลบองค์ประกอบสุดท้าย
    list1.pop_back();
    cout << "The list after deleting last element using pop_back() : ";
    for(auto i = list1.begin(); i != list1.end(); i++)
        cout << *i << " ";
    cout << endl;
    
    return 0;
}

เอาต์พุต

The original list is : 10 15 20 25 30 35
The list after deleting first element using pop_front() : 15 20 25 30 35
The list after deleting last element using pop_back() : 15 20 25 30