I’m trying to figure out a way to merge 2 vectors and an integer into one vector. ie
return data.push_back(fn(data1), mid, fn(data2));
NB This is a recursive function. The vector data has values stored in it before it reaches the return statement. I need the values in data to be updated with the values in the return statement.
I have absolutely no idea how to go about doing this. I’ve been searching for a couple of hours, but nothing seems to work!
Any guidance is very much appreciated.
std::vector::insert()accepts an iterator range:You can also use
std::copy()from<algorithm>andstd::back_inserter()from<iterator>:However,
insert()can know the size of its input range in advance andreserve()the appropriate amount of memory, whileback_insert_iteratoris opaque—it just repeatedly callspush_back(). They both run in linear time, butinsert()will probably make fewer allocations.If the elements of your vectors are more efficient to move than to copy, you can use the C++11
std::make_move_iterator()from<iterator>to adapt the input ranges:Though I doubt this would make a difference for
int.