简体   繁体   中英

How to std::merge two std::vector in-place?

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 ?

Checking std::merge reference:

The behavior is undefined if the destination range overlaps either of the input ranges (the input ranges may overlap each other).

Thus, you can't use std::merge for in-place merging. Try writing a merge function and you will know why.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM