Open In App

How to Declare a List in C++?

Last Updated : 27 Mar, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, list is a data structure used to store elements sequentially in non-contiguous memory locations. This container implements doubly linked list which contains pointers to both previous and next elements in the sequence. In this article, we will learn how to declare a list in C++.

Declare a List in C++

To declare a list in C++, we use the std::list template from the STL library, specifying the type of elements the list will store, such as integers. We can then add elements using the list::push_back method and iterate through the list to access and print its elements.

Syntax to Declare a List in C++

 list<dataType> list_name;

here,

  • dataType: is the type of data that a list will store.
  • list_name: is the name of the list container.

C++ Program to Declare a List

The following program illustrates how we can declare a list in C++:

C++
// C++ Program to illustrates how we can declare a list
#include <iostream>
#include <list>
using namespace std;

int main()
{
    // Declaring an empty list of integers
    list<int> listData;

    // Adding elements to the list
    listData.push_back(10);
    listData.push_back(20);
    listData.push_back(30);
    listData.push_back(40);

    // Printing the elements of the list
    cout << "List elements:";
    for (int num : listData) {
        cout << " " << num;
    }
    cout << endl;

    return 0;
}

Output
List elements: 10 20 30 40

Time Complexity: O(N) , where N is the number of list elements
Auxiliary Space: O(N)




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads