刪除 C++ STL 列表中的元素


在本教程中,我們將討論一個程式來了解如何在 C++ STL 列表中刪除元素。

為此,我們將使用 pop_back() 和 pop_front() 函式分別從末尾和開頭刪除元素。

示例

 線上示例

#include<iostream>
#include<list>
using namespace std;
int main(){
   list<int>list1={10,15,20,25,30,35};
   cout << "The original list is : ";
   for (list<int>::iterator i=list1.begin(); i!=list1.end();i++)
   cout << *i << " ";
   cout << endl;
   //deleting first element
   list1.pop_front();
   cout << "The list after deleting first element using pop_front() : ";
   for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
   cout << *i << " ";
   cout << endl;
   //deleting last element
   list1.pop_back();
   cout << "The list after deleting last element using pop_back() : ";
   for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
   cout << *i << " ";
   cout << endl;
}

輸出

The original list is : 10 15 20 25 30 35
The list after deleting first element using pop_front() : 15 20 25 30 35
The list after deleting last element using pop_back() : 15 20 25 30

更新於: 23-03-2020

150 次瀏覽

開啟你的 職業生涯

完成課程並獲得認證

開始學習
廣告
© . All rights reserved.