Specifying List size and initializing all values
Another way to initialize a list is by assigning a particular value to all the elements of the list. In this method, we pass a desired size for the list and the value to be stored for all the elements of that size.
Syntax:
list<data_type> li(n,val); // Here list li is initialized with size as n and values as val.
Example:
C++
// C++ program to specifying size // and initializing all values in list #include<bits/stdc++.h> using namespace std; int main() { int n = 4; // Create a list of size n with // all values as 1. list< int > li(n,1); // Printing the List for ( int x : li) cout << x << " " ; return 0; } |
Output
1 1 1 1
Different Ways to Initialize a List in C++ STL
Prerequisite: List in C++
Lists are sequence containers that allow non-contiguous memory allocation The following are the different ways to create and initialize a List in C++ STL.
- Initializing an empty List and pushing values one by one
- Specifying List size and initializing all values
- Initializing List like the arrays
- Initializing a list from an array
- Initializing a list from a vector
- Initializing a list from another List
- Initializing the List using the fill() function
- Using a lambda expression and the generate() function: