2

What's the best way to extend a vector with the contents of a vector returned from a function?

I can do:

std::vector<int> base;
{
    std::vector<int> tmp = getVec(); //RVO will make this efficient
    base.reserve(base.size() + tmp.size());
    base.insert(base.end(), std::make_move_iterator(tmp.begin()), std::make_move_iterator(tmp.end()));
}

But is it possible to do it without creating tmp? I could pass base in to getVec by reference, but I feel parameters should be for inputs and the return value for outputs. Ideally I would be able to do:

base.extend(getVec());

But I can't see how to do this with the normal vector functions.

R. Martinho Fernandes
  • 228,013
  • 71
  • 433
  • 510
engie
  • 2,569
  • 3
  • 18
  • 13
  • 2
    `append(base, getVec());`, which has the appropriate body to do the moving and stuff. Basically, moving the temporary `std::vector` from a local variable to a parameter. – Xeo Jul 11 '13 at 16:19

1 Answers1

-1

Send the vector you want to append to as a parameter. This is widely used and accepted.

void func(vector<int>* master) {
   // Generate values as you did in getVec() but now append to the original vector
   // instead of to a temp. 
   while(generatingNumbers(i))
       master->push_back(i);
}
Nate Rubin
  • 752
  • 1
  • 7
  • 12
  • This is not C++, is C. Why a pointer if you have references? And this type of function is not the correct way to do this type of things. Checkout @Xeo's comment at OP's question. Thats the good way. Compiler uses move semantics. – Manu343726 Jul 11 '13 at 16:46