Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

return a vector vs use a parameter for the vector to return it

Tags:

With the code below, the question is:

If you use the "returnIntVector()" function, is the vector copied from the local to the "outer" (global) scope? In other words is it a more time and memory consuming variation compared to the "getIntVector()"-function? (However providing the same functionality.)

#include <iostream>
#include <vector>
using namespace std;

vector<int> returnIntVector()
{
   vector<int> vecInts(10);
   for(unsigned int ui = 0; ui < vecInts.size(); ui++)
      vecInts[ui] = ui;

   return vecInts;
}

void getIntVector(vector<int> &vecInts)
{
   for(unsigned int ui = 0; ui < vecInts.size(); ui++)
      vecInts[ui] = ui;
}

int main()
{
   vector<int> vecInts = returnIntVector();
   for(unsigned int ui = 0; ui < vecInts.size(); ui++)
      cout << vecInts[ui] << endl;
   cout << endl;

   vector<int> vecInts2(10);
   getIntVector(vecInts2);
   for(unsigned int ui = 0; ui < vecInts2.size(); ui++)
      cout << vecInts2[ui] << endl;

   return 0;
}
like image 500
AudioDroid Avatar asked Aug 23 '11 14:08

AudioDroid


People also ask

Does returning a vector copy?

The return by value is the preferred method if we return a vector variable declared in the function. The efficiency of this method comes from its move-semantics. It means that returning a vector does not copy the object, thus avoiding wasting extra speed/space.

Can we return a vector from a function in C++?

Yes, functions in C++ can return a value of type std::vector .


1 Answers

In theory, yes it's copied. In reality, no, most modern compilers take advantage of return value optimization.

So you can write code that acts semantically correct. If you want a function that modifies or inspects a value, you take it in by reference. Your code does not do that, it creates a new value not dependent upon anything else, so return by value.

like image 75
Benjamin Lindley Avatar answered Sep 22 '22 17:09

Benjamin Lindley