Open In App

How to Create a Vector of Arrays in C++?

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

In C++, an array is a collection of elements of a single type while vectors are dynamic arrays as they can change their size during the insertion and deletion of elements. In this article, we will learn how to create a vector of arrays in C++.

Example:

Input: 
arr1 = {1, 2, 3};
arr2 = {4, 5, 6};
arr3 = {7, 8, 9};

Output:
Vector of Arrays: {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}

Creating a Vector of Arrays in C++

To create a vector of arrays in C++, we can use the std::array container provided by the STL library. The std::array is a container that encapsulates fixed-size arrays. We can then create a vector of these arrays using the following syntax:

Syntax to Declare Vector of Arrays

vector< array<datatype, size> > vec_name;

Here,

  • datatype denotes the type of data you want to store in the arrays.
  • size denotes the size of each array present in the vector.
  • vec_name is the name of the vector of vector.

Note: To declare a vector of plain old datatype arrays, we must store them as pointers as the vector elements should be copy constructible and assignable, and arrays is neither of them.

C++ Program to Create a Vector of Arrays

The below program demonstrates how we can create a vector of arrays in C++ STL.

C++
// C++ Program to illustrate how to create a vector of
// arrays
#include <array>
#include <iostream>
#include <vector>
using namespace std;

int main()
{

    // Initializing a vector of arrays of size 4
    vector<array<int, 4> > vec;

    // Create arrays to insert into the vector
    array<int, 4> arr1{ { 1, 2, 3, 4 } };
    array<int, 4> arr2{ { 6, 7, 8, 9 } };

    // Insert the arrays into the vector
    vec.push_back(arr1);
    vec.push_back(arr2);

    // Print the vector of arrays
    cout << "Elements in a Vector are: " << endl;
    for (auto& arr : vec) {
        for (auto& el : arr)
            cout << el << ' ';
    }

    return 0;
}

Output
Elements in a Vector are: 
1 2 3 4 6 7 8 9 

Time Complexity: O(N), here N is the number of arrays.
Auxiliary Space: O(N * M), where M is the average size of the arrays.




Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads