c++ STL set difference
Does the C++ STL set data structure have a set difference operator?
Yes there is, it is in <algorithm>
and is called: std::set_difference
. The usage is:
#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()));
In the end, the set result
will contain the s1-s2
.
Yes, there is a set_difference function in the algorithms header.
Edits:
FYI, the set data structure is able to efficiently use that algorithm, as stated in its documentation. The algorithm also works not just on sets but on any pair of iterators over sorted collections.
As others have mentioned, this is an external algorithm, not a method. Presumably that's fine for your application.
Not an "operator" in the language sense, but there is the set_difference algorithm in the standard library:
http://www.cplusplus.com/reference/algorithm/set_difference.html
Of course, the other basic set operations are present too - (union etc), as suggested by the "See also" section at the end of the linked article.
C++ does not define a set difference operator but you can define your own (using code given in other responses):
template<class T>
set<T> operator -(set<T> reference, set<T> items_to_remove)
{
set<T> result;
std::set_difference(
reference.begin(), reference.end(),
items_to_remove.begin(), items_to_remove.end(),
std::inserter(result, result.end()));
return result;
}