在C++ STL中移除()函式列表
在本文中我們將討論C++中的remove()函式的原理、語法和示例。
什麼是STL中的列表
列表是一種資料結構,允許在序列的任何位置進行恆定時間的插入和刪除。列表實現為雙向連結串列。列表允許非連續記憶體分配。列表的插入提取和在容器中任何位置移動元素的效能優於陣列、向量和雙端佇列。在列表中,對元素的直接訪問很慢,列表類似於forward_list,但是forward list物件是單鏈表,它們只能向前迭代。
什麼是remove()
remove()是C++ STL中的一個內建函式,在標頭檔案中宣告。remove()用於從列表容器中刪除任何特定值/元素。它使用作為引數傳遞的值,並從列表容器中刪除所有具有該值的所有元素。如果被移除元素的大小大於列表容器的大小,則該函式將呼叫解構函式。
語法
list_name.remove(const value_type& value);
此函式接受一個值,該值需要從列表容器中搜索並被刪除。
返回值
此函式不返回任何內容,只是從容器中移除元素。
示例
/*
In the code below we are inserting elements to the list and then we will try to remove the elements from the list using their values. */
#include <bits/stdc++.h>
using namespace std;
int main(){
//create a list
list<int> myList;
//insert elements to the List
myList.push_back(1);
myList.push_back(1);
myList.push_back(3);
myList.push_back(2);
myList.push_back(5);
//my list before removing elements
cout<<"List before removing elements: ";
for (auto i = myList.begin(); i!=myList.end(); i++){
cout << *i << " ";
}
//deleting 1 2 and 3 from the list
myList.remove(1);
myList.remove(2);
myList.remove(3);
// List after removing elements
cout << "\nList after removing elements: ";
for (auto i = myList.begin(); i!= myList.end(); i++){
cout << *i << " ";
}
return 0;
}輸出
如果我們執行上面的程式碼,它會生成下列輸出
List before removing elements: 1 1 3 2 5 List after removing elements: 5
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP