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 ?
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.
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));
//...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With