In this article we will discuss the different ways to initialize a std::list in C++.

std::list provides various overloaded constructors for creation and initialization of list. Let’s see different ways to create & initialize a std::list in C++ i.e.

Creating an Empty List in C++

std::list has a default constructor that will create an empty list i.e.

Let’s see an example to create an empty list and the push elements in it i.e

Output:

As above example contains c++11 range based for loop, so to compile the above example use following command,

Creating & Initializing a List with Fill Constructor

In this example we will create a List using its Fill Constructor i.e.

It will create a list with 5 elements and each is initialized with a copy of element passed as second argument i.e. 119 in our case.

Example of initializing a list with Fill Constructor is as follows,

Output:

As above example contains c++11 range based for loop, so to compile the above example use following command,

Creating & Initializing a List with c++11’s initializer_list

In C++11 new overloaded constructor of std::list is introduced that can receive an initializer_list as argument and can initialize list elements with a copy of elements in initializer_list i.e.

 

Lets see an example to initialize a std::list with an initialzer_list i.e.

Output:

As above example contains c++11 range based for loop, so to compile the above example use following command,

Initializing a std::list with a std::vector or an Array

std::list provides an over loaded version of constructor that accepts a range i.e.

Let’s use this to initialize a std::list with a Vector i.e.

Initializing a std::list from an array using above mentioned constructor,

Output of above 2 Examples:

As above example contains c++11 range based for loop, so to compile the above example use following command,