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 t开发者_开发技巧his?
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}
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
I would use std::set_difference
, which runs in O(n) time.
精彩评论