c++partitioning

std::partition_copy: what happens when the d_first_true output range overlaps with the input range?


for example:

int original_range[] = {1, 2, 3, 4, 5, 6, 7};
int copy_here[7];

std::partition_copy(std::begin(original_range), std::end(original_range),
                    std::begin(original_range), std::begin(copy_here),
                    [](int val) { return val >= 4; });

I'm expecting here: original_range = {4, 5, 6, 7, 5, 6, 7} and copy_here = {1, 2, 3, 0, 0, 0, 0}
you can assume that the garbage values stored in copy_here are 0.


Solution

  • Your code invokes UB (Undefined Behavior), and therefore anything can happen.

    from std::partition_copy documentation:

    Among the input range and the two output ranges, if any two ranges overlap, the behavior is undefined.

    (emphasis is mine)

    In your case the first output range overlaps with the input range, and so UB ensues. There is no point rationalising about the program output.

    Also note that:

    int copy_here[7];
    

    leaves the elements uninitialized. If you read those which did not get initialied by the algorithm, you get into another UB.
    You can fix it by using:

    //--------------vv-
    int copy_here[7]{};
    

    This will initialize all elements to zero.