0

When I declare a vector like vector<vector<int> >v and try to pass it to a function like below it works:

int change(vector<vector<int> >&v)
{
    v[0][0]=-1;
}
int main()
{
    vector<vector<int> >v;
    int a[]={1,2,3};
    int b[]={4,5,6};
    v.push_back(vector<int>(a,a+3));
    v.push_back(vector<int>(b,b+3));
    change(v);
    cout<<v[0][0];
return 0;
}

But when I declare the vector like vector<int>v[2] and pass it to a function in the same way it's causing an error.

int change(vector<vector<int> >&v)
{
    v[0][0]=-1;
}
int main()
{
    vector<int>v[2];
    int a[]={1,2,3};
    int b[]={4,5,6};
    v[0]=vector<int>(a,a+3);
    v[1]=vector<int>(b,b+3);
    change(v);
    cout<<v[0][0];
return 0;
}

How can I do this and why is this causing an error?

Luís Cruz
  • 14,780
  • 16
  • 68
  • 100
Sakib Ahammed
  • 2,452
  • 2
  • 25
  • 29
  • The answers to [your previous question](http://stackoverflow.com/questions/28712364/difference-between-vector-int-v-and-vector-vectorint-v) tell you that `vectorv[2]` is an array of vectors, not a "2D vector". – juanchopanza Feb 25 '15 at 10:32

2 Answers2

1

In the second example you declared an array of vector.

So you can use either :

int change(vector<int>(&v)[2])

or

int change(vector<int>v[]) // pointer

or

int change(vector<int>*v) // pointer
Ali Akber
  • 3,670
  • 3
  • 26
  • 40
  • Those are passing a pointer to vector, not a vector by reference. – juanchopanza Feb 25 '15 at 10:39
  • both works fine and i think it fullfils the expectation of OP... what's wrong if i pass the vector this way? – Ali Akber Feb 25 '15 at 10:41
  • What is wrong is you are saying it is passing by reference, but it really is passing a pointer to vector. Any pointer. It can be null, it can be a pointer to a single vector, it can be a pointer to an array of length 1 or 10000. You throw away the type information for no reason. – juanchopanza Feb 25 '15 at 11:20
  • Your answer still has the same problems. – juanchopanza Feb 25 '15 at 12:34
-2

how in hell could this work, you want implicit conversion from vector<int>[] to vector<vector<int>> ? a vector is a object containing things, an array isn't that

note that an array dont need to be passed by reference, so

int change(vector<int> v[])

do the trick

Guiroux
  • 531
  • 4
  • 11