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

forward_list::push_front() và pop_front() trong C++ STL


Trong bài viết này, chúng ta sẽ thảo luận về hoạt động, cú pháp và ví dụ của forward_list::push_front() và forward_list::pop_front() trong C++.

forward_list::push_front()

Hàm push_front() chèn một phần tử hoặc giá trị vào đầu (phía trước) của forward_list. Phần tử đầu tiên hiện có trở thành phần tử thứ hai, phần tử mới chèn thành phần tử đầu tiên, kích thước container tăng 1.

Cú pháp

flist_container1.push_front(const value_type& value);

Nhận một tham số: giá trị chèn vào đầu.

Giá trị trả về

Không trả về giá trị.

Ví dụ push_front()

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

int main() {
    forward_list<int> forwardList = {12, 21, 22, 24};
    forwardList.push_front(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;
}

Đầu ra

Forward List contains: 78 12 21 22 24
Forward List after performing sort operation: 12 21 22 24 78

forward_list::pop_front()

Hàm pop_front() xóa phần tử ở đầu forward_list. Phần tử đầu tiên bị xóa, phần tử kế tiếp trở thành phần tử đầu mới, kích thước giảm 1.

Cú pháp

flist_container1.pop_front();

Không nhận tham số.

Giá trị trả về

Không trả về giá trị.

Ví dụ 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();
    cout << "\nlist after applying pop operation: ";
    for (auto j = forwardList.begin(); j != forwardList.end(); ++j) cout << ' ' << *j;
}

Đầu ra

list before applying pop operation: 10 20 30
list after applying pop operation: 20 30