Initialize a std::list in C++

In this post, we will see 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 initializer lists '{...}' for initializing a list. This won’t work in C++98 as standard permits list to be initialized by 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 list from elements of another list, having 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 list from elements of an array or from 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 list of specified size 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

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 


Get great deals at Amazon




Categories

Leave a Reply

Notify of
avatar
wpDiscuz