tags:

views:

99

answers:

4

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 ?

+4  A: 
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));
    //...
}
Job
+7  A: 

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.

meagar
V is big , isn't it a bad practice to return a copy . Also , the size of the vector is determined *inside* the function so how can I pass it to the function and redefine its size ??
Ahmed
@Ahmed See updated answer. It's only bad practice to return-by-value (meaning by copying a variable) if you discover it's noticeable affecting performance. It looks like you're probably only calling this method once to initialize your data, if that's the case there will be no measurable difference in performance.
meagar
got it .Thank you !
Ahmed
As Job points out, you should be sure to `clear()` the vector if you're not sure that it will be empty.
meagar
It's also definitely worth noting RVO and NRVO. These compiler optimizations will effectively remove copies in returning by value by changing it to being the posted form of generate. You should always just return local variables by value, and manually do this optimization if profiling reveals a problem.
DeadMG
So RVO and NRVO eliminates the necessity of pass by reference in my case ?
Ahmed
A: 

if the vector is small, just return it by value, it will be copied. if the vector is large, the caller can pass the dest vector by reference.

Dustin Getz
I decide the size of the vector from inside this function .
Ahmed
vectors may be resized!
Dustin Getz
A: 
vnm