How to Resize a 2D Vector in C++?
Last Updated :
02 Feb, 2024
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++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector<vector< int > > vec(3, vector< int >(4));
cout << "Initial size - Rows: " << vec.size()
<< ", Columns: " << vec[0].size() << endl;
vec.resize(5, vector< int >(6));
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
Share your thoughts in the comments
Please Login to comment...