2

I am trying to return a vector from a function. But if I return the whole vector, then the copying process would take extra time, so I am trying to return a reference to the vector only. How do I do that in C++ ? here's my current function,

vector<ii>& primeFactors(int n)
    {
        int i;
        vector<ii> factors;
        for(i=0; i<=n && n!=1 ; ++i)
        {
            int cnt = 0;
            while((n%primes[i]) == 0)
            {
                ++cnt;
                n/=primes[i];
            }
            if(cnt!=0)
                factors.push_back({primes[i],cnt});
        }
        if(i == lim)
            factors.push_back({n,1});



        return factors;
    }

and heres my calling in main()

vector<ii> factors = primes.primeFactors(20);
Unbound
  • 243
  • 2
  • 12
  • 4
    Just return a value. It makes no sense to return a reference in this case. – juanchopanza Apr 14 '14 at 11:49
  • possible duplicate of [how to "return an object" in C++](http://stackoverflow.com/questions/3350385/how-to-return-an-object-in-c) – juanchopanza Apr 14 '14 at 11:50
  • @juanchopanza Not in this case, but there are a lot of situations where this makes sense. – Ben Apr 14 '14 at 11:51
  • 3
    What you try is not a good idea, since one should not return references to local variables. – Codor Apr 14 '14 at 11:53
  • 1
    If you want to do this, you will need to make the vector a reference PARAMETER of the function, and pass a vector to store the result from outside the function. Remember to clear the vector first. This can allow you to reuse the same vector which may be more performant in certain situations. – Neil Kirk Apr 14 '14 at 11:59

3 Answers3

4

But if I return the whole vector, then the copying process would take extra time, so I am trying to return a reference to the vector only.

Don't worry about that. The compiler will optimize the call via RVO (return value optimization) and elide the copies. Just return the vector by value:

std::vector<ii> primeFactors(int n) { … }
Shoe
  • 74,840
  • 36
  • 166
  • 272
2

As stated by others you should just return the vector.

But if for whatever reason you really want to return a reference you have to be sure that it "lives" after exiting the function. This is not the case with local variables as in your code.

Instead you could wrap the function in a class and have the vector as a member:

class PrimeFactorCalculator
{
public:
    std::vector<ii>& primeFactors(int n)
    {
        // ...

        return m_resultVector;
    }

private:
    std::vector<ii> m_resultVector;
};
TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52
0

You can either just return the value of the vector or you can pass the vector by reference as an argument to your function.

JNevens
  • 11,202
  • 9
  • 46
  • 72