简体   繁体   中英

How to return a vector reference from a function?

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

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) { … }

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

您可以只返回向量的值,也可以通过引用将向量作为参数传递给函数。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM