C++ STL 中的 List::clear()


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

什麼是 STL 中的 List?

List 是一種資料結構,它允許在序列中的任何位置進行常數時間插入和刪除操作。列表以雙向連結串列的形式實現。列表允許非連續記憶體分配。與陣列、向量和雙端佇列相比,列表在任何位置插入、提取和移動元素方面表現更好。在列表中,對元素的直接訪問速度較慢,並且列表類似於 forward_list,但 forward_list 物件是單向連結串列,它們只能向前迭代。

什麼是 clear()?

list::clear() 是 C++ STL 中的一個內建函式,它在標頭檔案中宣告。list::clear() 清空整個列表。換句話說,clear() 刪除列表容器中存在的所有元素,並使容器的大小為 0。

語法

list_name.clear();

此函式不接受任何引數。

返回值

此函式不返回任何內容,只是從容器中刪除所有元素。

示例

在下面的程式碼中,我們將元素插入列表,然後應用 clear 函式清空整個列表,使其為空。

 即時演示

#include <iostream>
#include <list>
using namespace std;
int main(){
   list<int> myList = { 10, 20, 30, 40, 50 };
   cout<<"List before applying clear() function";
   for (auto i = myList.begin(); i != myList.end(); ++i)
   cout << ' ' << *i;
   //applying clear() function to clear the list
   myList.clear();
   for (auto i = myList.begin(); i!= myList.end(); ++i)
      cout << ' ' << *i;
   cout<<"\nlist is cleared ";
   return 0;
}

輸出

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

List before applying clear() function 10 20 30 40 50
list is cleared

示例

在下面的程式碼中,我們將使用 clear() 函式清空整個列表,然後將新元素重新插入列表並顯示相同內容。

 即時演示

#include <iostream>
#include <list>
using namespace std;
int main (){
   list<int> myList;
   std::list<int>::iterator i;
   myList.push_back (10);
   myList.push_back (20);
   myList.push_back (30);
   cout<<"List before applying clear() function";
   for (auto i = myList.begin(); i != myList.end(); ++i)
      cout << ' ' << *i;
   myList.clear();
   for (auto i = myList.begin(); i!= myList.end(); ++i)
   cout << ' ' << *i;
   cout<<"\nlist is cleared ";
   myList.push_back (60);
   myList.push_back (70);
   cout<<"\nelements in my list are: ";
   for (auto i=myList.begin(); i!=myList.end(); ++i)
      cout<< ' ' << *i;
   return 0;
}

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

List before applying clear() function 10 20 30 40 50
list is cleared
Elements in my list are : 60 70

更新時間: 2020年2月26日

4K+ 閱讀量

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告

© . All rights reserved.