Reputation: 89
I am trying to use a large 2D vector which I want to allocate with new (because it is large).
if I say:
vector< vector<int> > bob;
bob = vector< vector<int> >(16, vector<int>(1<<12,0));
bob[5][5] = 777;
it works. But if I say:
std::vector< std::vector<int> > *mary;
mary = new vector< vector<int> >(16, vector<int>(1<<12, 0));
mary[5][5] = 777;
it doesn't work and I get the error:
Error 1 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'int' (or there is no acceptable conversion) c:\Users\jsparger\Documents\My Dropbox\ARI\VME_0.01\VME_0.01\V965.cpp 11 VME_0.01
Obviously I am new to C++. Could someone explain what syntax I need to use to perform this operation. mary is a pointer, so I can see why this wouldn't work, but *mary[5][5] = whatever is not allowed either because of "new", right?
Thanks for the help. This vector is what I will be using for now because it seems easy enough for my small c++ brain to understand, but feel free to let me know if a large vector like this is a bad idea, etc.
Thanks a bunch.
Edit: I am mistaken about the "not allowed because of new". I don't know where I misread that, because it obviously works, and wouldn't make too much sense for it not to. Thanks.
Upvotes: 1
Views: 1759
Reputation: 23629
In plain C, arrays and pointers are similar (not the same!), which leads to your confusion. In plain C, if you have the following declarations:
int array1[100];
int *array2 = (int *)malloc(100*sizeof(int));
you can use array1 and array2 in exactly the same way.
However, if you write this in C:
int (*array3)[100];
This is something completely different. Array3 is now a pointer to an array, not a pointer to the elements of the array anymore, and if you want to access an element, you have to write this:
(*array3)[5] = 123;
In C++, you are actually doing something similar, the second 'mary' is a pointer to the vector, not a pointer to the elements in the vector. Therefore, you have to write this:
(*mary)[5][5] = 777;
Upvotes: 2
Reputation: 263220
Vectors store their elements on the heap, anyway. There's no point in allocating the vector object itself on the heap, since it is very small (typically 12 bytes on a 32-bit machine).
Upvotes: 6
Reputation: 355187
If mary
is a pointer then you have to dereference it before applying the subscript operator:
(*mary)[5][5] = 777;
The parentheses are required because the subscript has higher precedence than the dereference.
Upvotes: 6