Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set difference in C++

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}
like image 770
user620189 Avatar asked Apr 18 '11 12:04

user620189


People also ask

How to take set difference in c++?

std::set_difference in C++ The difference of two sets is formed by the elements that are present in the first set, but not in the second one. The elements copied by the function come always from the first range, in the same order. The elements in the both the ranges shall already be ordered.

What is the difference between two sets?

The difference of two sets, written A - B is the set of all elements of A that are not elements of B. The difference operation, along with union and intersection, is an important and fundamental set theory operation.

What is symmetric difference in C?

Symmetric Difference basically contains all elements of two arrays except common elements. Symmetric difference of two array is the all array elements of both array except the elements that are presents in both array. SymmDiff = (arr1 - arr2) UNION (arr2 - arr1).

How do you find symmetric difference in C++?

C++ Algorithm set_symmetric_difference() function is used to find the symmetric difference between two sorted ranges[first1, last1) and [first2, last2), which is formed by the elements and is present in one of the range, but not in the other.


1 Answers

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

like image 57
orlp Avatar answered Sep 23 '22 21:09

orlp