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}
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.
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.
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).
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With