สมมติว่าเรามีรายการ STL หนึ่งรายการใน C++ มีองค์ประกอบน้อย เราต้องแทรกองค์ประกอบใหม่ลงในรายการ เราสามารถแทรกที่จุดสิ้นสุดหรือจุดเริ่มต้นหรือตำแหน่งใดก็ได้ ให้เราดูโค้ดเดียวเพื่อความเข้าใจที่ดีขึ้น ในการแทรกที่จุดเริ่มต้น เราจะใช้ 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