C++ STL 中的 forward_list::remove()


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

什麼是 STL 中的 Forward_list?

正向列表是序列容器,它允許對序列中的任何位置進行恆定時間插入和刪除操作。正向列表以單鏈表方式實現。透過將每個元素與序列中下一個元素的連結關聯起來保持排序。

什麼是 forward_list::remove()?

forward_list::remove() 是一項 C++ STL 中的內建函式,在標頭檔案中進行宣告。remove() 用於從正向列表中刪除所有元素。會根據刪除的元素數量減少容器大小。

語法

flist_container1.remove(const value_type& value );

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

返回值

此函式不返回任何值

示例

在下面的程式碼中,我們

 動態演示

#include <forward_list>
#include <iostream>
using namespace std;
int main(){
   forward_list<int> forwardList = {2, 3, 1, 1, 1, 6, 7};
   //List before applying remove operation
   cout<<"list before applying remove operation : ";
   for(auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
   //List after applying remove operation
   cout<<"\nlist after applying remove operation : ";
   forwardList.remove(1);
   for(auto i = forwardList.begin(); i != forwardList.end(); ++i)
      cout << ' ' << *i;
}

輸出

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

list before applying remove operation : 2, 3, 1, 1, 1, 6, 7
list after applying remove operation : 2, 3, 6, 7

更新於: 2020-03-02

300 次瀏覽

開啟你的 職業生涯

完成課程後即可獲得認證

開始
廣告
© . All rights reserved.