如何在 C++ STL 列表中插入元素?


假設我們在 C++ 中有一個 STL 列表。其中有一些元素。我們需要在列表中插入一個新元素。我們可以在末尾、開頭或任意位置進行插入。讓我們看一個程式碼,以便更好地理解。要在開頭插入,我們將使用 push_front(),要在末尾插入,我們將使用 push_end(),要在任意位置插入,我們需要使用一些操作。我們需要初始化一個迭代器,然後將該迭代器移到正確的位置,然後使用 insert() 方法進行插入。

示例

 線上演示

#include<iostream>
#include<list>
using namespace std;
void display(list<int> my_list){
   for (auto it = my_list.begin(); it != my_list.end(); ++it)
   cout << *it << " ";
}
int main() {
   int arr[] = {10, 41, 54, 20, 23, 69, 84, 75};
   int n = sizeof(arr)/sizeof(arr[0]);
   list<int> my_list;
   for(int i = 0; i<n; i++){
      my_list.push_back(arr[i]);
   }
   cout << "List before insertion: ";
   display(my_list);
   //insert 100 at front
   my_list.push_front(100);
   //insert 500 at back
   my_list.push_back(500);
   //insert 1000 at index 5
   list<int>::iterator it = my_list.begin();
   advance(it, 5);
   my_list.insert(it, 1000);
   cout << "\nList after insertion: ";
   display(my_list);
}

輸出

List before insertion: 10 41 54 20 23 69 84 75
List after insertion: 100 10 41 54 20 1000 23 69 84 75 500

更新於: 17-12-2019

439 檢視

開啟你的職業生涯

完成課程並獲得認證

開始
廣告