Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pointer to a multidimensional vector

Tags:

c++

I am trying to initialize a pointer (*vectorName) with a 2D vector 366 by 4.

Both

vector<int> *vectorName = new vector<int>(366, new vector<int>(4));

and

vector<int> *vectorName = new vector<int>(366, vector<int>(4));

do not work and give me the error

Error: no instance of constructor "std::vector, <_Ty, _Alloc>::vector [with_ty=int, _Alloc=std_allocator]" argument types are (const int, std::vector>*)

What can I do?

This is happening within the main function.

like image 467
kclausch Avatar asked Oct 26 '25 09:10

kclausch


1 Answers

vector<int> *vectorName = new vector<int>(366, vector<int>(4));

The above doesn't work because the vector constructor template (ignoring a few things) looks as follows:

vector <TYPE> (SIZE, variable of type TYPE);

And in vector<int>(366, vector<int>(4)), vector <int> (4) is not of type int.

To create a vector with 366 elements that are vector of ints of size 4:

vector<vector<int> > *vectorName = new vector<vector<int> >(366, vector<int>(4));

or, if you don't need a pointer: (which you quite possibly don't)

vector<vector<int> > vectorName(366, vector<int>(4));

As a side note, if it's a fixed size 2D vector, why are you using vector, and not just an array. This would be much simpler:

int arr[366][4];
like image 140
Bernhard Barker Avatar answered Oct 28 '25 21:10

Bernhard Barker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!