views:

3870

answers:

6

Does the C++ STL set data structure have a set difference operator?

+7  A: 

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.

Mr Fooz
It's usable on _any_ pair of sorted containers.
xtofl
Good point...I've added a note in the edits.
Mr Fooz
A: 

Not as a method but there's the external algorithm function set_difference

template <class InputIterator1, class InputIterator2, class OutputIterator>
OutputIterator set_difference(InputIterator1 first1, InputIterator1 last1,
                              InputIterator2 first2, InputIterator2 last2,
                              OutputIterator result);

http://www.sgi.com/tech/stl/set_difference.html

Ian G
A: 

Apparently, it does.

SGI - set_difference

Jason Lepack
+3  A: 

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.

Phil Nash
+23  A: 

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.

PierreBdR
+1. Sadly, when I needed that, I gave up and rolled my own loop :(
peterchen
BTW, if you use set_difference on a non-associative container class, say a vector, make sure the elements in both containers are sorted first...
ceretullis
#include <algorithms> -> No such file, should be <algorithm> ?
stefanB
for set<string> I had to qualify std::insert_iterator< set<string >>(...)
stefanB
@stefanB: first comment is correct, and as to the second one: common is to use `std::inserter` instead. No qualification is needed since this is a function.
rlbond
A: 

The chosen answer is correct, but has some syntax errors.

Instead of

#include <algorithms>

use

#include <algorithm>

Instead of

std::insert_iterator(result, result.end()));

use

std::insert_iterator<set<int> >(result, result.end()));
or just use `std::inserter(result, result.end())`
rlbond