The Wayback Machine - https://web.archive.org/web/20241003165123/https://www.geeksforgeeks.org/insert-elements-c-stl-list/
Open In App

How to insert elements in C++ STL List ?

Last Updated : 13 Sep, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

List has been discussed in many articles, but the sole purpose of this article is to cover all types of insertions that are possible to be carried in a list container and to give a detailed insight on the insertion operations.
List and its many functions are defined under the header file “list” . Various list insertions functions are discussed below.

Using assign()

assign() function is used to insert multiple elements in a list in a single operation. “assign()” works in following ways :

  • To insert multiple elements at once in a list.
    syntax : list.assign(number of times, element).
  • To copy elements of 1 list into another.
    syntax : list.assign(lis2.begin(),lis2.end())
  • To copy array elements into list.
    syntax : list.assign(arr,arr+size).




// C++ code to demonstrate the working of assign()
  
#include <iostream>
#include <list> // for list operations
using namespace std;
  
int main() 
{
    // declaring list
    list<int> list1;
    list<int> list2;
    list<int> list3;
      
    // initializing array
    int arr[10] = { 1, 2, 3, 4 };
      
    // using assign() to insert multiple numbers
    // creates 4 occurrences of "2"
    list1.assign(4,2);
      
    // Printing the assigned list
    cout << "The list after inserting multiple elements is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
    // using assign() to copy elements of list to other
    // assigns 4 occurrences of "2"
    list2.assign(list1.begin(),list1.end());
      
    // Printing the assigned list
    cout << "The list after copying list elements is : ";
    for (list<int>::iterator i=list2.begin(); i!=list2.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
    // using assign() to copy elements of array to list
    // assigns array elements
    list3.assign(arr,arr+4);
      
    // Printing the assigned list
    cout << "The list after copying array elements is : ";
    for (list<int>::iterator i=list3.begin(); i!=list3.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
}


Output:

The list after inserting multiple elements is : 2 2 2 2 
The list after copying list elements is : 2 2 2 2 
The list after copying array elements is : 1 2 3 4 

Insertion at beginning

  • Using push_front() : push_front() is used to insert the element at the beginning of list. Increases list size by 1.
  • Using emplace_front() : Works in a similar way as push_front, but the values are constructed in-place in front position of container, where in push_front, an object is created first, and then copied to the container.




// C++ code to demonstrate the working of 
// push_front() and emplace_front()
  
#include <iostream>
#include <list> // for list operations
using namespace std;
  
int main() 
{
    // declaring list
    list<int> list1;
      
    // using assign() to insert multiple numbers
    // creates 2 occurrences of "2"
    list1.assign(2,2);
      
    // using push_front to insert elements at beginning
    // inserts 5 at beginning
    list1.push_front(5);
      
    // Printing the new list
    cout << "The list after inserting elements using push_front is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
    // using emplace_front to insert elements at beginning
    // inserts 7 at beginning
    list1.emplace_front(7);
      
    // Printing the new list
    cout << "The list after inserting elements using emplace_front is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";    
}


Output:

The list after inserting elements using push_front is : 5 2 2 
The list after inserting elements using emplace_front is : 7 5 2 2 

Insertion at end

  • Using push_back() : push_back() is used to insert the element at the end of list. Increases list size by 1.
  • Using emplace_back() : Works in a similar way as push_back, but the values are constructed in-place at back position of container, where in push_back, an object is created first, and then copied to the container.




// C++ code to demonstrate the working of 
// push_back() and emplace_back()
  
#include <iostream>
#include <list> // for list operations
using namespace std;
  
int main() 
{
    // declaring list
    list<int> list1;
      
    // using assign() to insert multiple numbers
    // creates 2 occurrences of "2"
    list1.assign(2,2);
      
    // using push_back to insert elements at the end
    // inserts 5 at end
    list1.push_back(5);
      
    // Printing the new list
    cout << "The list after inserting elements using push_back is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
    // using emplace_back to insert elements at the end
    // inserts 7 at end
    list1.emplace_back(7);
      
    // Printing the new list
    cout << "The list after inserting elements using emplace_back is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
}


Output:

The list after inserting elements using push_back is : 2 2 5 
The list after inserting elements using emplace_back is : 2 2 5 7 

Insertion at any position

  • Using insert(pos_iter,ele_num,ele) : insert() is used to insert the elements at any position of list.
  • . This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1.

  • Using emplace(pos_iter,ele) : Works in a similar way as insert(), but the values are constructed in-place in front position of container, where in push_front, an object is created first, and then copied to the container. And only 1 value is allowed to insert at 1 time.




// C++ code to demonstrate the working of 
// insert() and emplace()
  
#include <iostream>
#include <list> // for list operations
using namespace std;
  
int main() 
{
    // declaring list
    list<int> list1;
      
    // using assign() to insert multiple numbers
    // creates 3 occurrences of "2"
    list1.assign(3,2);
      
    // initializing list iterator to beginning
    list<int>::iterator it = list1.begin();
      
    // iterator to point to 3rd position
    advance(it,2);
      
    // using insert to insert 1 element at the 3rd position
    // inserts 5 at 3rd position
    list1.insert(it,5);
      
    // Printing the new list
    cout << "The list after inserting 1 element using insert() is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
    // using insert to insert 2 element at the 4th position
    // inserts 2 occurrences of 7 at 4th position
    list1.insert(it,2,7);
      
    // Printing the new list
    cout << "The list after inserting multiple elements using insert() is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
    cout << endl;
      
    // using emplace to insert elements at the 6th position
    // inserts 8 at 6th position
    list1.emplace(it,8);
      
    // Printing the new list
    cout << "The list after inserting elements using emplace() is : ";
    for (list<int>::iterator i=list1.begin(); i!=list1.end(); i++)
       cout << *i << " ";
      
}


Output:

The list after inserting 1 element using insert() is : 2 2 5 2 
The list after inserting multiple elements using insert() is : 2 2 5 7 7 2 
The list after inserting elements using emplace() is : 2 2 5 7 7 8 2 



Previous Article
Next Article

Similar Reads

Different Ways to Insert Elements in Set in C++ STL
Prerequisites: Set in C++ The C++ Standard Template Library offers containers called Sets. It functions essentially in the same ways as a binary search tree and is used to store different elements in increasing/decreasing order. There are different methods to insert elements in the set as mentioned below: Adding one element to setInserting an Itera
3 min read
How to Insert a Range of Elements in a Set in C++ STL?
Prerequisites: Set in C++ Sets in C++ are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending. Syntax: set<datatype> set_name; Some Basic Functions Associated with Set: begin(): Returns an ite
2 min read
list insert() in C++ STL
The list::insert() is used to insert the elements at any position of list. This function takes 3 elements, position, number of elements to insert and value to insert. If not mentioned, number of elements is default set to 1. Syntax: insert(pos_iter, ele_num, ele)Parameters: This function takes in three parameters: pos_iter: Position in the containe
2 min read
emplace vs insert in C++ STL
In C++, all containers (vector, stack, queue, set, map, etc) support both insert and emplace operations. Both are used to add an element in the container.The advantage of emplace is, it does in-place insertion and avoids an unnecessary copy of object. For primitive data types, it does not matter which one we use. But for objects, use of emplace() i
1 min read
multimap insert() in C++ STL
The multimap::insert is a built-in function in C++ STL that is used to insert elements in the multimap container. Syntax: iterator multimap_name.insert({key, element}) Parameters: The function accepts a pair that consists of a key and element which is to be inserted into the multimap container. Return Value: The function returns an iterator pointin
2 min read
multiset insert() function in C++ STL
The multiset::insert() is a built-in function in C++ STL which insert elements in the multiset container or inserts the elements from a position to another position from one multiset to a different multiset. Syntax: iterator multiset_name.insert(element)Time Complexity: O(log n) Since the elements are always in sorted order, the newly inserted elem
4 min read
deque insert() function in C++ STL
The deque::insert() function is a built-in function in C++ which is used to insert elements in the deque. The insert() function can be used in three ways: Extends deque by inserting a new element val at a position.Extends deque by inserting n new element of value val in the deque.Extends deque by inserting new element in the range [first, last). Sy
3 min read
unordered_map insert in C++ STL
The unordered_map::insert() is a built-in function in C++ STL which is used to insert elements with a particular key in the unordered_map container. This function increases container size by 1. This function does not insert duplicate entries. There are following variant of this function. All are overloaded functions. Syntax-1: iterator unordered_ma
3 min read
vector insert() Function in C++ STL
The std::vector::insert() is a built-in function in C++ STL that inserts new elements before the element at the specified position, effectively increasing the container size by the number of elements inserted. It is a member function of std::vector class template. The insert function is overloaded to work on multiple cases which are as follows: Tab
4 min read
map insert() in C++ STL
The std::map::insert() is a built-in function of C++ STL map container which is used to insert new elements into the map. In this article, we will learn how to use map::insert() function in our C++ programs. The map::insert() function can insert elements in the following ways: Table of Content Insert a Single ElementInsert an Element Near the Given
5 min read
set::insert() function in C++ STL
The std::set::insert() is a built-in function of C++ STL set container which is used to insert new elements in it. In this article, we will learn how to use set::insert() function in our C++ programs. Following are the different ways in which we can insert elements in an std::set container using set::insert() method: Table of Content Insert a Singl
4 min read
Delete elements in C++ STL list
How to insert elements in C++ STL List ? This article covers the deletion aspects in STL list. Using list::erase(): The purpose of this function is to remove the elements from list. Single or multiple contiguous elements in range can be removed using this function. This function takes 2 arguments, start iterator and end iterator. Time complexity :
4 min read
list::push_front() and list::push_back() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::push_front() push_front() function is used to push elements into a list from the front. The n
4 min read
list::pop_front() and list::pop_back() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::pop_front() pop_front() function is used to pop or remove elements from a list from the front
4 min read
list::front() and list::back() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::front() This function is used to reference the first element of the list container. This func
3 min read
list::empty() and list::size() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::empty()empty() function is used to check if the list container is empty or not. Syntax : list
3 min read
list::remove() and list::remove_if() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::remove() remove() function is used to remove all the values from the list that correspond to
3 min read
list::emplace_front() and list::emplace_back() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::emplace_front()This function is used to insert a new element into the list container, the new
3 min read
list::begin() and list::end() in C++ STL
Lists are containers used in C++ to store data in a non-contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::begin() begin() function is used to return an iterator pointing to the first element of the l
3 min read
Inserting elements in std::map (insert, emplace and operator [])
Prerequisite: Map in STL The map is a container, as the name suggests used to store a key-value pair. The map has an advantage over other containers by the fact that searching in the map, defined by the "key" takes only O(logn) time complexity, hence making it useful in various coding fields. The insertion is discussed in this article. 1. Using ins
8 min read
How to insert a Node in a Singly Linked List at a given Position using Recursion
Given a singly linked list as list, a position, and a node, the task is to insert that element in the given linked list at a given position using recursion. Examples: Input: list = 1->2->3->4->5->6->7, node = (val=100,next=null), position = 4 Output: 1->2->3->100->4->5->6->7Explanation: Here the node with valu
14 min read
How to find common elements between two Arrays using STL in C++?
Given two arrays, find common elements between these two arrays using STL in C++. Example: Input: arr1[] = {1, 45, 54, 71, 76, 12}, arr2[] = {1, 7, 5, 4, 6, 12} Output: {1, 12} Input: arr1[] = {1, 7, 5, 4, 6, 12}, arr2[] = {10, 12, 11} Output: {1, 4, 12} Approach: Common elements can be found with the help of set_intersection() function provided in
2 min read
How to find common elements between two Vector using STL in C++?
Given two vectors, find common elements between these two vectors using STL in C++. Example: Input: vec1 = {1, 45, 54, 71, 76, 12}, vec2 = {1, 7, 5, 4, 6, 12} Output: {1, 12} Input: vec1 = {1, 7, 5, 4, 6, 12}, vec2 = {10, 12, 11} Output: {1, 4, 12} Approach: Common elements can be found with the help of set_intersection() function provided in STL.
2 min read
How to find the sum of elements of a Vector using STL in C++?
Given a vector, find the sum of the elements of this vector using STL in C++. Example:Input: vec = {1, 45, 54, 71, 76, 12} Output: 259 Input: vec = {1, 7, 5, 4, 6, 12} Output: 35Approach: Sum can be found with the help of accumulate() function provided in STL. Syntax:accumulate(first_index, last_index, initial value of sum); C/C++ Code // C++ progr
2 min read
Elements present in first array and not in second using STL in C++
Given two arrays, the task is that we find numbers which are present in first array, but not present in the second array, using STL in C++ Examples: Input: a[] = {1, 2, 3, 4, 5, 10}, b[] = {2, 3, 1, 0, 5} Output: 4 10 Input:a[] = {4, 3, 5, 9, 11}, b[] = {4, 9, 3, 11, 10}; Output: 5 Approach: In STL, the set_difference() method can be used to find t
2 min read
Remove duplicate elements in an Array using STL in C++
Given an array, the task is to remove the duplicate elements from the array using STL in C++ Examples: Input: arr[] = {2, 2, 2, 2, 2} Output: arr[] = {2} Input: arr[] = {1, 2, 2, 3, 4, 4, 4, 5, 5} Output: arr[] = {1, 2, 3, 4, 5} Approach: This can be done using set in standard template library. Set type variable in STL automatically removes duplica
2 min read
std::transform() in C++ STL (Perform an operation on all elements)
Consider the problem of adding contents of two arrays into a third array. It is given that all arrays are of same size. Following is simple C++ program without transform(). C/C++ Code // A C++ code to add two arrays #include <bits/stdc++.h> using namespace std; int main() { int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n = sizeof(arr1)/
2 min read
Quickly check if two STL vectors contain same elements or not
Unlike normal C/C++ arrays, we don't need to do element by element comparison to find if two given vectors contain same elements or not.In case of vectors, the operator "==" is overloaded to find the result quickly. Below is an example to demonstrate same. C/C++ Code // C++ implementation to check whether elements // in vector is equal or not #incl
1 min read
Sort elements by frequency using STL
Given an array of integers, sort the array according to frequency of elements. If frequencies of two elements are same, print them in increasing order. Examples: Input : arr[] = {2, 3, 2, 4, 5, 12, 2, 3, 3, 3, 12} Output : 3 3 3 3 2 2 2 12 12 4 5 Explanation : No. Freq 2 : 3 3 : 4 4 : 1 5 : 1 12 : 2Recommended PracticeSorting Elements of an Array b
7 min read
list::clear() in C++ STL
Lists are containers used in C++ to store data in a non contiguous fashion, Normally, Arrays and Vectors are contiguous in nature, therefore the insertion and deletion operations are costlier as compared to the insertion and deletion option in Lists. list::clear()clear() function is used to remove all the elements of the list container, thus making
1 min read
Practice Tags :