Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

list::push_front() và list::push_back() trong C++ STL

list: danh sách liên kết kép, chèn/xóa O(1) bất kỳ vị trí, cấp phát bộ nhớ không liên tục.

list::push_front()

Thêm phần tử vào đầu danh sách. Size tăng 1.

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

int main() {
    list<int> myList;
    myList.push_front(10); myList.push_front(20); myList.push_front(30);
    myList.push_front(40); myList.push_front(50); myList.sort();
    cout << "Elements in the list are: ";
    for (auto i = myList.begin(); i != myList.end(); ++i) cout << ' ' << *i;
    return 0;
}

Đầu ra

Elements in the list are: 10 20 30 40 50

list::push_back()

Thêm phần tử vào cuối danh sách. Size tăng 1.

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

int main() {
    list<int> myList;
    myList.push_back(10); myList.push_back(20); myList.push_back(30);
    myList.push_back(40); myList.push_back(50); myList.sort();
    cout << "Elements in the list are: ";
    for (auto i = myList.begin(); i != myList.end(); ++i) cout << ' ' << *i;
    return 0;
}

Đầu ra

Elements in the list are: 10 20 30 40 50