Create Array of Arrays for std::array Container in C++

In C++, we have a wrapper container class for arrays named std::array. We can also create arrays of this type of array container f you are using the below syntax:

Syntax

std::array<std::array<dataType, COLS>, ROWS> matrix = {{  {x,y,z} .... }};

where:

  • data_type: denotes the type of data you want to store in the array of arrays.
  • Matrix: is the name of the array of arrays.
  • ROWS: denotes the number of rows in your array of arrays.
  • COLS: denotes the number of columns in your array of arrays.

C++ Program to Create std::Array of Arrays

The following program demonstrates how we can create array of arrays using std::arrays in C++:

C++
// C++ Program to demonstrate how we can create array of
// arrays using std::arrays
#include <array>
#include <iostream>
using namespace std;

// Declare the dimensions for the arrays of arrays
const int ROWS = 3;
const int COLS = 3;

int main()
{
    // Initialize an array of arrays
    array<array<int, COLS>, ROWS> matrix
        = { { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } } };

    // Print all elements
    for (int i = 0; i < ROWS; ++i) {
        for (int j = 0; j < COLS; ++j) {
            cout << matrix[i][j] << " ";
        }
        cout << endl;
    }

    return 0;
}

Output
1 2 3 
4 5 6 
7 8 9 

Time Complexity:O(N*M) where N denotes the number of rows and M denotes the number of columns.
Auxiliary Space:O(N*M)





How to Create Array of Arrays in C++

Arrays are basic C++ data structures that allow users to store the same data type in memory sequentially. To manage more complicated data structures, you may sometimes need to build an array of arrays, often called a 2D array or a matrix. In this article, we will learn how to create an array of arrays in C++.

Similar Reads

Create an Array of Arrays in C++

To create an array of arrays also known as 2D arrays, you can follow the same approach you follow to create a normal one-dimensional array with some minor changes. Like in normal one-dimensional arrays, you define only the number of columns for the array here you will have to define an additional dimension row along with the number of columns. Here is the syntax to create an array of arrays in C++:...

Create Array of Arrays for std::array Container in C++

In C++, we have a wrapper container class for arrays named std::array. We can also create arrays of this type of array container f you are using the below syntax:...