Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Declaring a 2D vector

Tags:

c++

stl

vector

In some cases only the below line works.Why so?

vector< vector<int>> a(M,N); 

This works in every case.

vector< vector<int>> a(M, vector<int> (N)); 

What's the difference?

like image 845
sad Avatar asked Feb 22 '15 21:02

sad


People also ask

How do you define 2D vectors?

A 2D vector is a vector of the vector. Like 2D arrays, we can declare and assign values to a 2D vector! Assuming you are familiar with a normal vector in C++, with the help of an example we demonstrate how a 2D vector differs from a normal vector below: C++

Are there 2 dimensional vectors C++?

A 2-Dimensional vector is used in C++ programming to store and access data based on rows and columns. Different ways to create a 2-Dimensional vector have been shown in this tutorial by using simple examples.


2 Answers

std::vector has a fill constructor which creates a vector of n elements and fills with the value specified. a has the type std::vector<std::vector<int>> which means that it is a vector of a vector. Hence your default value to fill the vector is a vector itself, not an int. Therefore the second options is the correct one.

std::vector<std::vector<int>> array_2d(rows, std::vector<int>(cols, 0));

This creates a rows * cols 2D array where each element is 0. The default value is std::vector<int>(cols, 0) which means each row has a vector which has cols number of element, each being 0.

like image 166
a_pradhan Avatar answered Sep 29 '22 22:09

a_pradhan


For declaring a 2D vector we have to first define a 1D array of size equal to number of rows of the desired 2D vector. Let we want to create a vector of k rows and m columns

 "vector<vector<int>> track(k);" 

This will create a vector of size k. Then use resize method.

for (int i = 0; i < k; i++) {     track[i].resize(m); 

In this way you can declare a 2D vector

like image 24
user10636234 Avatar answered Sep 29 '22 23:09

user10636234