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

forward_list::push_front() และ pop_front() ใน C++ STL

forward_list::push_front() และ pop_front() ใน C++ STL

Forward List ใน STL

Singly-linked list รองรับ insertion/erasure แบบ constant time ใดๆ ในลำดับ แต่เข้าถึงแบบ random ไม่ได้ (ไม่มี operator[])

forward_list::push_front()

แทรกองค์ประกอบใหม่ที่ด้านหน้า (head) ของ list ขนาดเพิ่ม 1

Syntax

flist.push_front(const value_type& value);

ตัวอย่าง

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

int main() {
    forward_list<int> forwardList = {12, 21, 22, 24};
    
    forwardList.push_front(78);  // เพิ่ม 78 ที่หน้า
    
    cout << "Forward List contains: ";
    for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
        cout << ' ' << *i;
    
    forwardList.sort();  // เรียงลำดับ
    
    cout << "\nForward List after performing sort operation: ";
    for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
        cout << ' ' << *i;
    return 0;
}

Output: Forward List contains: 78 12 21 22 24 → after sort: 12 21 22 24 78

forward_list::pop_front()

ลบองค์ประกอบตัวแรก (head) ของ list ขนาดลด 1

Syntax

flist.pop_front();

ตัวอย่าง

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

int main() {
    forward_list<int> forwardList = {10, 20, 30};
    
    cout << "list before applying pop operation: ";
    for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
        cout << ' ' << *i;
    
    forwardList.pop_front();  // ลบ 10
    
    cout << "\nlist after applying pop operation: ";
    for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
        cout << ' ' << *j;
    return 0;
}

Output: before: 10 20 30 → after: 20 30

ฟังก์ชันหน้าที่คล้ายกัน

  • emplace_front() - สร้าง object inplace ที่หน้า (C++11)
  • front() - เข้าถึงค่าตัวแรก (reference)
  • before_begin() - iterator ก่อน begin (สำหรับ insert_after/erase_after)

ข้อจำกัด

  • ไม่มี push_back(), pop_back(), back() (เพราะ singly-linked)
  • ต้องใช้ insert_after/erase_after กับ before_begin() สำหรับการดำเนินการกลาง list