Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to use constructors to initialize a 2D Vector as a one-liner in C++?

Is it okay to initialize a 2D vector like this (here all values in a 5x4 2D vectro are initialized to 3)?

std::vector<std::vector<int> > foo(5, std::vector<int>(4, 3));

This seems to behave okay, but everywhere I look on the web people seem to recommend initializing such a vector with for loops and push_back(). I was initially afraid that all rows here would point to the same vector, but that doesn't seem to be the case. Am I missing something?

like image 762
Richard Bradley Avatar asked Mar 11 '11 19:03

Richard Bradley


People also ask

How do you initialize a 2D vector?

The 2D vector can be initialized with a user-defined size as well. It is similar to using the new operator or malloc() to create a 2D dynamic array. Consequently, if we want to establish a 2D vector to rows n and columns m, we must start a 2D vector of size n with elements from a 1D vector of size m.

Which of the following is the correct way to initialize a 2D vector of integers?

Using Fill Constructor The recommended approach is to use a fill constructor to initialize a two-dimensional vector.

How do you initialize a 2D vector in a class C++?

To initialize a two-dimensional vector to be of a certain size, you can first initialize a one-dimensional vector and then use this to initialize the two-dimensional one: vector<int> v(5); vector<vector<int> > v2(8,v); or you can do it in one line: vector<vector<int> > v2(8, vector<int>(5));


2 Answers

Well, the code is valid and it indeed does what you want it to do (assuming I understood your intent correctly).

However, doing it that way is generally inefficient (at least in the current version of the language/library). The above initialization creates a temporary vector and then initializes individual sub-vectors by copying the original. That can be rather inefficient. For this reason in many cases it is preferrable to construct the top-level vector by itself

std::vector<std::vector<int> > foo(5);

and then iterate over it and build its individual sub-vectors in-place by doing something like

foo[i].resize(4, 3);
like image 36
AnT Avatar answered Sep 29 '22 03:09

AnT


This is perfectly valid - You'll get a 2D vector ([5, 4] elements) with every element initialized to 3.

For most other cases (where you e.g. want different values in different elements) you cannot use any one-liner - and therefore need loops.

like image 124
Erik Avatar answered Sep 29 '22 04:09

Erik