Initializing an empty List and pushing values one by one
The standard way to initialize a list is to first create an empty list and then elements are added to that list using the inbuilt list_name.push_back() method.
Syntax:
list<data_type> li; li.push_back(ele); // Here list li is initialized and element ele is inserted into that list.
Example:
C++
// C++ program to create an empty List // and push values one by one. #include <bits/stdc++.h> using namespace std; int main() { // Create an empty List list< int > li; // Adding values to the List li.push_back(10); li.push_back(20); li.push_back(30); // 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: