To initialize a list in C++ using std::list
, you can use the default constructor for an empty list or provide elements during the list's construction.
In this example,
std::list
to create an empty list of integers and assign it to the variable empty_list
.#include <iostream>
#include <list>
int main() {
std::list<int> empty_list;
std::cout << "Empty List initialized." << std::endl;
return 0;
}
Empty List initialized.
In this example,
std::list
and provide initial values to create a list of integers.numbers
.#include <iostream>
#include <list>
int main() {
std::list<int> numbers = {1, 2, 3, 4, 5};
std::cout << "List with Elements: ";
for (int num : numbers) {
std::cout << num << " ";
}
std::cout << std::endl;
return 0;
}
List with Elements: 1 2 3 4 5
In this tutorial, we learned How to Initialize a List in C++ language with well detailed examples.