1

I have a 2d vector that needs to be allocated on the heap and am using the below line of code to declare and size it.

vector<vector<double>> *myArray = new vector<vector<double>>(x, vector<double>(y));

where x and y are the number of rows and columns respectively.

When I try to access an element of the vector using myArray[0][0] = 3.0;, I get the following error,

error: no viable overloaded '='

myArray[0][0] = 3.0;

I would appreciate any help in figuring this out.

Notes:

  1. The number of rows and columns needs to be dynamic, hence myArray is on the heap.

  2. The array needs to be resizable, which is why I am using std::vector.

  3. I understand that I can create a vector of vectors (number of rows) and then in a for-loop resize each row element to the required number of columns. What I do not understand is why the above code does not work since as far as I know it should perform the same function.

trincot
  • 317,000
  • 35
  • 244
  • 286
muppet
  • 51
  • 4

2 Answers2

5

For some strange invalid reason, you are using a pointer to a vector. Since operator[] works with pointers, when you do

myArray[0][0] = 3.0;

you are actually accessing a vector<double>, not a double, because myArray[0] gets you a vector<vector<double>>.

The obvious fix is not to use a pointer in the first place:

vector<vector<double>> myArray(x, vector<double>(y));
juanchopanza
  • 223,364
  • 34
  • 402
  • 480
  • Thanks, I understand what is going on now. I am using a pointer since the 2dim vector `myArray` is encapsulated in a class. The constructor accepts the number of rows and columns as arguments and initializes the memory on the heap using `new`. I was trying to not have to resize each row individually in a loop if the array is declared on the stack. Any thoughts? – muppet Jan 17 '15 at 11:46
  • @muppet Just initialize it like I showed. You really don't need a pointer to a newed object. – juanchopanza Jan 17 '15 at 17:05
2

must be:

(*dataArray)[0][0] = 3.0
Arashium
  • 325
  • 2
  • 9
  • 3
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. – Nerdroid Jan 17 '15 at 12:22
  • If it fix the problem, why cannot be an answer? it is not clarification request nor critique. – Arashium Jan 17 '15 at 12:27
  • OP wanted help figuring out the problem. Your one line does just (maybe) gives working piece of code, it does not really help in figuring out what was wrong originally. – hyde Jan 17 '15 at 15:54