c++ - How to return a vector reference from a function? -


i trying return vector function. if return whole vector, copying process take time, trying return reference vector only. how do in c++ ? here's 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 calling in main()

vector<ii> factors = primes.primefactors(20); 

but if return whole vector, copying process take time, trying return reference vector only.

don't worry that. compiler optimize call via rvo (return value optimization) , elide copies. return vector value:

std::vector<ii> primefactors(int n) { … } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -