Initialize a std::list in C++
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 '{...}'.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <list> int main() { std::list<char> chars { 'A', 'B', 'C' }; for (char c: chars) { std::cout << c << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <list> int main() { std::list<char> another_list = { 'A', 'B', 'C' }; // copy constructor std::list<char> chars(another_list); for (char c: chars) { std::cout << c << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#include <iostream> #include <list> int main() { char ch[] = { 'A', 'B', 'C' }; std::list<char> chars(std::begin(ch), std::end(ch)); // or do initialize like this // std::list<char> chars(ch, ch + sizeof(ch)/sizeof(char)); for (char c: chars) { std::cout << c << std::endl; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <list> int main() { unsigned size = 3; char ch = 'A'; // fill constructor std::list<char> chars(size, ch); for (char c: chars) { std::cout << c << std::endl; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
#include <iostream> #include <list> int main() { std::list<char> chars; for (char c: chars) { std::cout << c << std::endl; } return 0; } |
That’s all about initializing a std::list in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)