C++ STL 中的 forward_list::push_front() 和 forward_list::pop_front()


在本文中,我們將討論 C++ 中 forward_list::push_front() 和 forward_list::pop_front() 函式的工作原理、語法和示例。

什麼是 STL 中的 Forward_list?

Forward list 是一種序列容器,允許在序列中的任何位置進行常數時間插入和刪除操作。Forward list 以單向連結串列的形式實現。順序由每個元素與序列中下一個元素的連結來維護。

什麼是 forward_list::push_front()?

forward_list::push_front() is an inbuilt function in C++ STL which is declared in
header file. push_front() is used to push/insert an element or a value in the front or at the
beginnig of the forward_list. When we use this function the first element which is already in the
container becomes the second, and the element pushed becomes the first element of the
forward_list container and the size of the container is increased by 1.

語法

flist_container1.push_front (const value_type& value );

此函式只能接受一個引數,即要插入到開頭位置的值。

返回值

此函式不返回任何值。

push_front()

示例

在下面的程式碼中,我們使用 push_front() 操作將元素插入到列表的開頭,然後使用 sort() 函式對列表元素進行排序。

即時演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {12, 21, 22, 24};
   //inserting element in the front of a list using push_front() function
   forwardList.push_front(78);
   cout<<"Forward List contains: ";
   for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   //list after applying sort operation
   forwardList.sort();
   cout<<"\nForward List after performing sort operation : ";
   for (auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

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

什麼是 forward_list::pop_front()?

forward_list::pop_front() 是 C++ STL 中的一個內建函式,它在 <forward_list> 標頭檔案中宣告。pop_front() 用於彈出/刪除 forward_list 開頭的元素。當我們使用此函式時,容器中已存在的第一個元素將被刪除,第一個元素的下一個元素成為 forward_list 容器的第一個元素,並且容器的大小減少 1。

語法

flist_container1.pop_front ();

此函式不接受任何引數

返回值

此函式不返回任何值。

pop_front()

示例

在下面的程式碼中,我們使用 C++ STL 中存在的 pop_front() 操作刪除列表的第一個元素。

即時演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {10, 20, 30 };
   //List before applying pop operation
   cout<<"list before applying pop operation : ";
   for(auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   //List after applying pop operation
   cout<<"\nlist after applying pop operation : ";
   forwardList.pop_front();
   for (auto j = forwardList.begin(); j != forwardList.end(); ++j)
      cout << ' ' << *j;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出

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

更新於: 2020-03-02

245 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.