# How to insert elements in C++ STL List?

C++Server Side ProgrammingProgramming

#### C in Depth: The Complete C Programming Guide for Beginners

45 Lectures 4.5 hours

#### Practical C++: Learn C++ Basics Step by Step

Most Popular

50 Lectures 4.5 hours

#### Master C and Embedded C Programming- Learn as you go

Best Seller

66 Lectures 5.5 hours

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