Lists are sequence containers that allow non-contiguous memory allocation. As compared to vector, list has slow traversal, but once a position has been found, insertion and deletion are quick. Normally, when we say a List, we talk about doubly linked list. For implementing a singly linked list, we use forward list.
A list can be created with the help of constructor in C++. The syntax to do it is:
Syntax:
list<type> list_name(size_of_list, value_to_be_inserted);
Below programs show how to create a List with Constructor in C++.
Program 1:
#include <iostream> #include <list> using namespace std;
// Function to print the list void printList(list< int > mylist)
{ // Get the iterator
list< int >::iterator it;
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n' ;
} int main()
{ // Create a list with the help of constructor
// This will insert 100 10 times in the list
list< int > myList(10, 100);
printList(myList);
return 0;
} |
Output:
100 100 100 100 100 100 100 100 100 100
Program 2:
#include <bits/stdc++.h> using namespace std;
// Function to print the list void printList(list<string> mylist)
{ // Get the iterator
list<string>::iterator it;
// printing all the elements of the list
for (it = mylist.begin(); it != mylist.end(); ++it)
cout << ' ' << *it;
cout << '\n' ;
} int main()
{ // Create a list with the help of constructor
// This will insert Geeks 5 times in the list
list<string> myList(5, "Geeks" );
printList(myList);
return 0;
} |
Output:
Geeks Geeks Geeks Geeks Geeks