Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing array of vectors as a function parameter to change the original values

I have an array of vectors (of ints) and I want to pass it to a member function as reference so it can be modified. (It actually is the output of my function but I already have a return value.)

I wrote something like this

int Dag::dag2array(vector<int> (&aVectors)[4])
{ 
//some stuff
//calling another function tree2array(aVectors) 
//passing the same array as reference
}

It compile and runs although it looks like it is not doing what I want.

In a more or less opposite question (Passing array of vectors as a function parameter (values will not change)), the answers say that the array can be modified without & and that it does not make a copy but it is like a pointer.

  1. Why for a variable like an int one needs the & to avoid copying and to be able to modify the value of the original variable "on the fly" and not for an array?
  2. Should I use the & or not in my case?
like image 391
Prolix Avatar asked Dec 18 '25 19:12

Prolix


1 Answers

This is one of those cases where C arrays just make life difficult. I would strongly recommend using a std::array (or std::tr1::array if you're not using C++11 yet). Rather than that obscure syntax, saying

int func(std::array<std::vector<int>, 4>& vectors)

makes it very clear that you're passing an array of 4 vectors by reference, and thus can modify the values by saying

vectors[1][2] = 19;

or what-have-you.

like image 166
Tristan Brindle Avatar answered Dec 21 '25 10:12

Tristan Brindle