Computer Science, asked by KaranG2687, 1 year ago

Initializing vector of vectors of different sizes c++

Answers

Answered by liza10987654321
0

In C++, we can define a vector of vectors of ints as follows:

vector<vector<int>> v;

1

vector<vector<int>> v;

Above definition results in an empty two-dimensional vector. In order to use it, we have to define vector size and allocate storage for its elements. There are several methods to grow a two-dimensional vector with the help of resize() or push_back() functions, or using the fill constructor or initializer lists.

. resize() function

The resize() function is used to resize a vector to the specified size. We can use it to initialize a vector of vectors as shown below:

#include <iostream>

#include <vector>

using namespace std;

#define R 4

#define C 5

int main()

{

// instantiate a vector of R objects of type vector<int>

// and resize each object to size C

vector<vector<int>> mat(R);

for (int i = 0 ; i < R ; i++)

mat[i].resize(C);

// print the vector

return 0;

}

1#include <iostream>

2#include <vector>

3using namespace std;

4#define R 4

5#define C 5

6int main()

{

7 // instantiate a vector of R objects of type vector<int>

8 // and resize each object to size C

9 vector<vector<int>> mat(R);

10 for (int i = 0 ; i < R ; i++)

11 mat[i].resize(C);

12 // print the vector

13 return 0;

}

Similar questions