C++ Array of list with Examples

In this article, we will discuss the array of lists and some examples in C++. Before going into the topic let’s first discuss what are arrays and lists in C++.

Array and list in C++ :

Arrays are generally used to store elements of similar data types in continuous memory locations. Arrays are of fixed size, while declaring itself we have to mention the size and type of the array.

Syntax :

datatype arr_name[size];

Example :

int a[10];

Here is an array variable a, in which we can store at max 10 elements of integer type. We can access the elements of the arrays using indexes. Where indexing starts with 0, not 1 until size – 1.

Whereas, Lists in Cpp are known as containers which are used to store elements in non-continuous memory locations. Below is the syntax for declaring lists.

Syntax  :

list<datatype> name;

We will include <list> header file while using lists in our program. C++ provides some built-in functions for lists. They are front(), back(), push_front(v), push_back(v)size(), empty(), erase(), reverse(), sort(), insert() etc.

Array of list:

Array of lists means each element in the array is a list itself. Below is the syntax for the array of list declaration.

Syntax : 

list<datatype> container_name[size];

When we write int a[n], n elements in the array are integers similarly where each element is a list. Where the list has the mentioned datatype elements. We can use all the list functions for array of list. To understand array of list better let’s see an example code about, how to declare and initialize array of list.

Code :

// Online C++ compiler to run C++ program online
#include <iostream>
#include <list>
using namespace std;

void printList(list<int> &a)
{
    for(auto ele : a)
    {
        cout<<ele<<" ";
    }
    cout<<"\n";
}
int main() {
    int size = 2;
    list<int> a[size];
    //add elements to lists.at max 2 lists so, 0 and 1 index
    a[0].push_back(1);
    a[0].push_back(2);
    a[0].push_back(3);
    a[1].push_back(1);
    a[1].push_front(2);
    cout<<"Container elements are : "<<"\n";
    for(int i = 0;i < size; i++)
    {
        cout<<"list at index "<<i<<" is : ";
        printList(a[i]);
    }
    return 0;
}

Output : 

Container elements are : 
list at index 0 is : 1 2 3 
list at index 1 is : 2 1

In the above code initially, we declare an array of list of size 2. So we can insert two lists in the array. push_back() function in list is used to insert elements at the end, and push_front is used to insert elements at the front. Finally using a loop we traverse the array and at each index, we call a function to traverse through list elements at that index.

Leave a Reply

Your email address will not be published. Required fields are marked *