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);
5
  • 4
    Just return a value. It makes no sense to return a reference in this case. Commented Apr 14, 2014 at 11:49
  • possible duplicate of how to "return an object" in C++ Commented Apr 14, 2014 at 11:50
  • @juanchopanza Not in this case, but there are a lot of situations where this makes sense. Commented Apr 14, 2014 at 11:51
  • 3
    What you try is not a good idea, since one should not return references to local variables. Commented Apr 14, 2014 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. Commented Apr 14, 2014 at 11:59

3 Answers 3

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) { … }
Sign up to request clarification or add additional context in comments.

Comments

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;
};

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.