NoSenseEtAl
NoSenseEtAl

Reputation: 30118

Can output of set difference be stored in first input?

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.

Upvotes: 3

Views: 590

Answers (1)

Praetorian
Praetorian

Reputation: 109219

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.

Upvotes: 5

Related Questions