Home >>C++ Standard Template Library Tutorial(STL) >C++ List

C++ List

C++ List

A contiguous container that stores the elements on a contagious memory is known as the list in C++. On the other hand, vector is known as a non-contiguous container that strores the elements on a non-contiguous memory.

In the middle of the vector insertion and deletion can be done but it’s very expensive as there is a requirement of lot of time when it comes to shifting all the elements. In order to overcome this problem Linklist is used as it is implemented using list container.

List in C++ generally supports a bidirectional and delivers an efficient way for the process of insertion and deletion operations.

The list elements are generally accessed sequentially instead of accessing them randomly as in vector hence, traversal is slow in list.

Syntax

 

#include<iostream>  
#include<list>  
using namespace std;  
int main()  
{  
   list<int> l;  
}  

List can also be initalised with the parameters.

Syntax

#include<iostream>  
#include<list>  
using namespace std;  
int main()  
{  
   list<int> l{1,2,3,4};;  
}  

List can be initialised in two ways.

1st way

list<int>  new_list{1,2,3,4};  

2nd way

list<int> new_list = {1,2,3,4};  

C++ List Functions

Here is the list that contains every member function of the list:

Method Description
insert() This function is used to insert the new element before the position pointed by the iterator.
push_back() This function is used to add a new element at the end of the vector.
push_front() This function is used to add a new element to the front.
pop_back() This function is used to delete the last element.
pop_front() This function is used to delete the first element.
empty() This function is used to check whether the list is empty or not.
size() This function is used to find the number of elements present in the list.
max_size() This function is used to find the maximum size of the list.
front() This function is used to return the first element of the list.
back() This function is used to return the last element of the list.
swap() This function is used to swap two list when the type of both the list are same.
reverse() This function is used to reverse the elements of the list.
sort() This function is used to sort the elements of the list in an increasing order.
merge() This function is used to merge the two sorted list.
splice() This function is used to insert a new list into the invoking list.
unique() This function is used to remove all the duplicate elements from the list.
resize() This function is used to change the size of the list container.
assign() This function is used to assign a new element to the list container.
emplace() This function is used to insert a new element at a specified position.
emplace_back() This function is used to insert a new element at the end of the vector.
emplace_front() This function is used to insert a new element at the beginning of the list.

No Sidebar ads