How to concatenate / merge vectors

I am trying to find a way to merge 2 vectors and an integer into one vector. i.e

return data.push_back(fn(data1), mid, fn(data2)); 

NB This is a recursive function. Vector data has values ​​stored in it before it reaches the return statement. I need the values ​​in the data to be updated with the values ​​in the return statement.

I do not know how to do that. I searched for a couple of hours, but nothing works!

Any guidance is greatly appreciated.

+4
source share
3 answers

std::vector::insert() accepts a range of iterators:

 std::vector<int> left(fn(data1)); std::vector<int> right(fn(data2)); data.insert(data.end(), left.begin(), left.end()); data.push_back(mid); data.insert(data.end(), right.begin(), right.end()); return data; 

You can also use std::copy() from <algorithm> and std::back_inserter() from <iterator> :

 std::copy(left.begin(), left.end(), std::back_inserter(data)); data.push_back(mid); std::copy(right.begin(), right.end(), std::back_inserter(data)); 

However, insert() can know in advance the size of its input range and reserve() corresponding amount of memory, and back_insert_iterator opaque - it simply calls push_back() again. They both work in linear time, but insert() is likely to make fewer allocations.

If the elements of your vectors are more efficient for moving than for copying, you can use C ++ 11 std::make_move_iterator() from <iterator> to adapt the input ranges:

 data.insert(data.end(), std::make_move_iterator(left.begin()), std::make_move_iterator(left.end())); data.push_back(mid); data.insert(data.end(), std::make_move_iterator(right.begin()), std::make_move_iterator(right.end())); 

Although I doubt that this would affect the int .

+11
source

Use std::back_inserter along with std::copy . For instance:

 void foo(vector<int> lhs, vector<int>& rhs) { vector<int> result; copy( lhs.begin(), lhs.end(), back_inserter(result)); copy( rhs.begin(), rhs.end(), back_inserter(result)); result push_back(42); return result; } 
+1
source

You want to use an insert member function that takes 3 arguments of an iterator .

0
source

Source: https://habr.com/ru/post/1438726/


All Articles