Open In App

How to Resize a 2D Vector in C++?

Last Updated : 02 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In C++, a 2D vector, also known as a vector of vectors can be visualized as a matrix with particular height and width where each row itself is a vector. In this article, we’ll discuss how to resize a 2D vector in C++ according to the specified height and width.

Example

Input:
myVector = { {x, x ,x x},
                       {x, x, x, x} }
Output:
myVector = { {x, x ,x, x, x, x},
                       {x, x, x, x, x, x},
{x, x, x, x, x, x} }

Resize a Vector of Vector (2D Vector) in C++

A vector size can be changed to the desired value by using the std::vector::resize() function that changes the size of the vector to the value provided as the argument. We can apply this function first to the parent vector to change the height (number of rows) and then to each nested vector to change the width(number of columns).

C++ Program to Resize a 2d Vector

C++




// C++ Program to Resize a 2D Vector
  
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Initialize a 2D vector with 3 rows and 4 columns
    vector<vector<int> > vec(3, vector<int>(4));
  
    // Print the initial size of rows and columns
    cout << "Initial size - Rows: " << vec.size()
         << ", Columns: " << vec[0].size() << endl;
  
    // Resize the 2D vector to 5 rows and 6 columns
    vec.resize(5, vector<int>(6));
  
    // Print the final size of rows and columns
    cout << "Final size - Rows: " << vec.size()
         << ", Columns: " << vec[0].size() << endl;
  
    return 0;
}


Output

Initial size - Rows: 3, Columns: 4
Final size - Rows: 5, Columns: 4

Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads