How to insert elements in C++ STL List?

C++Server Side ProgrammingProgramming

Suppose we have one STL list in C++. There are few elements. We have to insert a new element into the list. We can insert at the end, or beginning or at any position. Let us see one code to get better understanding. To insert at beginning we will use push_front(), To insert at end, we will use push_end() and to insert at any position, we have to use some operations. we have to initialize one iterator, then move that iterator to correct position, then insert into that place using insert() method.

Example

 Live Demo

#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);
}

Output

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
raja
Published on 17-Dec-2019 13:12:51
Advertisements