This post will discuss how to initialize a std::list in C++.

There are several ways to initialize a list in C++, as listed below:

1. Initialize list from specified elements

In C++11 and above, we can use the initializer lists '{...}' to initialize a list. This won’t work in C++98 as standard permits list to be initialized by the constructor, not by '{...}'.

Download  Run Code

Output:

A
B
C

2. Initialize list from elements of another list

We can use a copy constructor to initialize a list from elements of another list having the same order of elements.

Download  Run Code

Output:

A
B
C

3. Initialize list from elements of an array

We can use a range constructor to initialize a list from elements of an array or another container.

Download  Run Code

Output:

A
B
C

4. Initialize a list of specified size by specified element

We can use a fill constructor to initialize a specified size list by specified element.

Download  Run Code

Output:

A
A
A

5. Initialize an empty list

Finally, we can use the default constructor to construct an empty list (with no elements), as shown below:

Download  Run Code

That’s all about initializing a std::list in C++.