Set difference in C++

user620189 picture user620189 · Apr 18, 2011 · Viewed 15.7k times · Source

If I know that one set is a subset of another set and I would like to find the difference, what's the most efficient way to do this?

ex. PSEUDO CODE

> set<int> set1 = {1 2 3 4 5 6 7 8 9 10}
> set<int> set2 = {5 6 7}

I want to subtract set2 from set1:

The answer here would be

{1 2 3 4 8 9 10}

Answer

orlp picture orlp · Apr 18, 2011

Use std::set_difference found in <algorithm>:

#include <algorithm>
#include <set>
#include <iterator>
// ...
std::set<int> s1, s2;
// Fill in s1 and s2 with values
std::set<int> result;
std::set_difference(s1.begin(), s1.end(), s2.begin(), s2.end(),
    std::inserter(result, result.end()));

Snippet source