How to create a List with Constructor in C++ STL

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


Output:

100 100 100 100 100 100 100 100 100 100

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

#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;
}

chevron_right


Output:

Geeks Geeks Geeks Geeks Geeks


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.