C++ STL 中的 list::pop_front() 和 list::pop_back()
在本文中,我們將討論 C++ STL 中 list::pop_front() 和 list::pop_back() 函式的工作原理、語法和示例。
什麼是 STL 中的列表?
列表是一種資料結構,允許在序列中的任何位置進行常數時間插入和刪除。列表以雙向連結串列的形式實現。列表允許非連續記憶體分配。與陣列、向量和雙端佇列相比,列表在容器的任何位置執行元素的插入、提取和移動方面表現更好。在列表中,對元素的直接訪問速度很慢,並且列表類似於 forward_list,但 forward_list 物件是單向連結串列,它們只能向前迭代。
什麼是 forward_list::pop_front()?
list::pop_front() 是 C++ STL 中的一個內建函式,它在標頭檔案中宣告。pop_front() 用於彈出/刪除列表開頭的元素。當我們使用此函式時,容器中已存在的第一個元素將被刪除,第一個元素的下一個元素將成為列表容器的第一個元素,並且容器的大小將減少 1。
語法
list_container1.pop_front ();
引數
此函式不接受任何引數。
返回值
此函式不返回任何內容。
示例
Input: list<int> List_container= {10, 11, 13, 15}; List_container.pop_front(); Output: List = 11 13 15
示例
#include <iostream> #include <list> using namespace std; int main(){ list<int> myList_1 = {}, myList_2 = {}; myList_1.push_front(10); myList_1.push_front(20); myList_1.push_front(30); myList_1.push_front(40); myList_1.push_front(50); while (!myList_1.empty()){ myList_2.push_front(myList_1.front()); myList_1.pop_front(); } cout<<"Elements in the list are : "; for (auto i = myList_2.begin(); i!= myList_2.end(); ++i) cout << ' ' << *i; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Elements in the list are : 10 20 30 40 50
什麼是 list::pop_back()?
list::pop_back() 是 C++ STL 中的一個內建函式,它在標頭檔案中宣告。pop_back() 用於從列表容器的末尾或最後一個位置刪除/彈出元素。當我們使用 pop_back 時,它會刪除/彈出最後一個元素,最後一個元素之前的元素將成為最後一個元素,並且列表容器的大小將減少 1。
語法
list_container.pop_back();
引數
此函式不接受任何引數。
返回值
此函式不返回任何內容。
示例
Input: list<int> List_container= {10, 11, 13, 15}; List_container.pop_back(); Output: List = 10 11 13
示例
#include <iostream> #include <list> using namespace std; int main(){ list<int> myList_1 = {}, myList_2 = {}; myList_1.push_front(10); myList_1.push_front(20); myList_1.push_front(30); myList_1.push_front(40); myList_1.push_front(50); while (!myList_1.empty()){ myList_2.push_front(myList_1.back()); myList_1.pop_back(); } cout<<"Elements in the list are : "; for (auto i = myList_2.begin(); i!= myList_2.end(); ++i) cout << ' ' << *i; }
輸出
如果我們執行以上程式碼,它將生成以下輸出:
Elements in the list are : 50 40 30 20 10
廣告