To create a list of size N in C++ using std::list, you can use the constructor that takes the initial size and default value as arguments.
In this example,
.std::list
constructor to create a list of size N with each element initialized to a default value.#include <iostream>
#include <list>
int main() {
int size = 5;
int default_value = 0;
std::list<int> mylist(size, default_value);
std::cout << "List of size " << size << " with default values: ";
for (int val : mylist) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
List of size 5 with default values: 0 0 0 0 0
In this example,
.std::list
constructor to create a list of size N with each element initialized to a specific value.#include <iostream>
#include <list>
int main() {
int size = 5;
int specific_value = 1;
std::list<int> mylist(size, specific_value);
std::cout << "List of size " << size << " with specific values: ";
for (int val : mylist) {
std::cout << val << " ";
}
std::cout << std::endl;
return 0;
}
List of size 5 with specific values: 1 1 1 1 1
In this tutorial, we learned How to create a List of size N in C++ language with well detailed examples.