C++ STL List Container – std::list

In this tutorial you will learn about C++ STL list container i.e. std::list and methods which can be applicable on it.

List comes under sequence containers. List stores elements in non-contiguous memory locations. List works same as double linked list. It can traverse in both directions. This is the reason list is slow in traversing when compared to vector. But it supports constant time insertion and removal of elements from anywhere in the container. If we want to implement single linked list then we should use forward list.

The main disadvantage by this list is, unlike other sequence containers elements of this container can’t be accessed by its index position.

C++ STL List

Declaring List

list<data_type> listName;

Operations Applicable on List Container

pus_front(x): It adds the new element ‘x’ at front of the list.

push_back(x): It adds the new element ‘x’ at the end of the list.

insert(): This function inserts the new elements to the list before the element at a specific position.

assign(): This erases the current elements of the list and adds new elements. Due to this replacement list size will change.

begin(): It returns the iterator pointing to the beginning of the list.

end(): This returns the iterator pointing to the last element of the list.

Example program to show ways to insert elements into list:

Output

2 34 44 44 1 0 11 12 13
50 50 50 50 50

Some more functions…

front(): It returns reference to the first element of the list.

back(): It returns reference to the current last element of the list.

pop_front(): This erases the first element of the list.

pop_back(): This erases the last element of the list.

erase(): It removes a single element or range of elements in from the list.

remove(x): It removes the all elements of the list which has value x .

empty(): This is Boolean type method. This returns whether the list is empty or not.

Example program to show all above functions:

Output

14 13 12 11 10
the first element of the list is 14
the last element of the list is 10
the first element after erasing current first elemnt is 13
the last element after erasing current last element is 11
remaining elements after doing all above operations
12 11
List is not empty
remaining elements after removing 11 are
12

reverse(): This reverse all the elements of the list.

sort(): Sorts the all elements in the list in increasing order.

size(): This returns the number of elements in the list.

Example program to show above functions:

Output

actual elements of the list are
4 2 0 1 3 5
Elements in the list after applying reverse operation
5 3 1 0 2 4
Elements in the list after applying sort operation
0 1 2 3 4 5
size of the lis is 6

Comment below if you have queries or found information incorrect in above tutorial for C++ STL List.

Leave a Comment

Your email address will not be published. Required fields are marked *