Following code attempts to std::merge v2 into v1.
std::vector<int> v1{1,2,3,0,0,0}; std::vector<int> v2{1,2,3}; std::merge(v1.begin(), v1.begin() + 3, v2.begin(), v2.end(), v1.begin()); for (auto i : v1) { std::cout << i << " "; } The expected output is: 1 1 2 2 3 3
The actual output by this code is : 1 1 1 1 2 3
A potential fix for this problem, is to create a temporary vector.
std::vector<int> v1{1,2,3,0,0,0}; std::vector<int> v2{1,2,3}; std::vector<int> tmp(v1.size()); std::merge(v1.begin(), v1.begin() + 3, v2.begin(), v2.end(), tmp.begin()); for (auto i : tmp) { std::cout << i << " "; } I want to avoid this memory overhead and do it in-place in vector v1. Any idea how I can do that with std::merge?
std::mergeexpects destination range doesn't overlap with either of the input ranges