Initializing a list from an array
One can also initialize the list from an array with the same data type.
Syntax:
list<data_type>li(old_array,old_array+size);
Here old_array is the array containing elements of the same data type as mentioned in the declaration of the list and size represents the length till which we want to copy the elements from an array to the list.
Below is the C++ program to implement the above approach:
C++
// C++ program to initialize the List // from array #include<bits/stdc++.h> using namespace std; int main() { int arr[] = { 10, 20, 30 }; int n = sizeof (arr) / sizeof (arr[0]); list< int > li(arr, arr + n); // Printing the List for ( int x : li) cout << x << " " ; return 0; } |
Output
10 20 30
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: