Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a 2 dimensional vector?

Tags:

c++

vector

I have a function that creates a 2D vector

void generate(int n)
{
   vector< vector<int> > V (n, vector<int>(1 << n , 0 ));
   .......

}//n is used to determine the size of vector

Now, I need to return the created vector to use it in another function .If I did

return V ;

it will be wrong because V is a local variable but I can't define V outside the function because this functions defines the size of V . What should I do ?

like image 736
Ahmed Avatar asked May 27 '26 17:05

Ahmed


2 Answers

You can return V with no issues - it will return a copy of the local variable. Issues only arise when you return a reference or pointer to a variable with local scope; when the function ends, the local variable falls out of scope and is destroyed and the reference/pointer is no longer valid.

Alternatively, you can accept a reference to a vector as your argument, write to it and return void:

void generate(int n, std::vector< std::vector<int> >& vec) {
    vec.resize(n, std::vector<int>(1 << n, 0));
}

int main() {
    std::vector< std::vector<int> > v;
    generate(10, v);
}

This is faster than returning a copy of the local member, which can be expensive for large objects such as multi-dimensional vectors.

like image 96
meagar Avatar answered May 30 '26 02:05

meagar


vector<vector<int> > generate(int n)
{
    vector<vector<int> > v(n, vector<int>(1 << n, 0));
    //...
    return v;
}

The return value is a copy of the local variable v so there is no problem at all.

If you're concerned about copying the vector, maybe you could do something like this:

void generate(int n, vector<vector<int> >& v)
{
    v.clear(); //not necessary if you're sure it's empty
    v.resize(n, vector<int>(1 << n, 0));
    //...
}
like image 28
mtvec Avatar answered May 30 '26 03:05

mtvec