Initializing the List using the fill() function
One can also initialize a list using the fill() function in C++. The ‘fill’ function assigns any particular value to all the elements in the given range. Here the range is provided with the help of iterators.
Syntax:
list<data_type> li(n); fill(li.begin(), li.end(), val); // Here, the list li is initialized with n as size and the value of all elements as val.
Example:
C++
// C++ program to initialize the List // using fill function #include<bits/stdc++.h> using namespace std; int main() { // Initialising the list list< int > li(3); int value = 10; fill(li.begin(), li.end(), value); // Printing theList for ( int x : li) cout << x << " " ; return 0; } |
Output
10 10 10
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: