Related Articles

Related Articles

How to create a List with Constructor in C++ STL
  • Last Updated : 18 Jan, 2019

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

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :