Can output of set difference be stored in first input?
Asked Answered
B

1

3

if I have 2 vectors(or deques):

can I store their set_difference in first vector?

Aka this example from cpp wiki reference:

std::vector<int> v1 {1, 2, 5, 5, 5, 9};
std::vector<int> v2 {2, 5, 7};
std::vector<int> diff;

std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), 
                    std::inserter(diff, diff.begin()));

Would it work if changed to :

std::vector<int> v1 {1, 2, 5, 5, 5, 9};
std::vector<int> v2 {2, 5, 7};

std::set_difference(v1.begin(), v1.end(), v2.begin(), v2.end(), 
                    v1.begin());

note by first input I mean first vector, and yes I know STL works on ranges, not on containers.

Bluegrass answered 17/1, 2014 at 17:2 Comment(0)
L
5

From N3797, §25.4.5.4/2 [set.difference]

Requires: The resulting range shall not overlap with either of the original ranges.

So the behavior would be undefined if you tried to write the result to either of the input ranges.

Lacey answered 17/1, 2014 at 17:8 Comment(3)
am i wrong to believe it would work for dest.begin() is exactly the same as first.begin(), aka they overspecified requirementsBluegrass
@Bluegrass The algorithm only requires InputIterators, hence single pass is guaranteed. So we know that once first.begin() has been read from, the algorithm won't read from it again, and what you're saying makes sense in that case. But maybe allowing the input range to be written was thought to be too restrictive on the implementation on the algorithm. For instance, maybe it's possible the algorithm can be made more efficient using multiple passes when passed a ForwardIterator or better.Lacey
Why would any algorithm use multiple passes or the like? To me it seems overspecified too.Sadden

© 2022 - 2024 — McMap. All rights reserved.