Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading