Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ STL set difference

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

like image 313
Steve Avatar asked Nov 12 '08 13:11

Steve


People also ask

What are sets in STL?

Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending.

What is difference between set and Unordered_set?

Set is an ordered sequence of unique keys whereas unordered_set is a set in which key can be stored in any order, so unordered. Set is implemented as a balanced tree structure that is why it is possible to maintain order between the elements (by specific tree traversal).

Which is better set or unordered set?

For a small number of elements, lookups in a set might be faster than lookups in an unordered_set . Even though many operations are faster in the average case for unordered_set , they are often guaranteed to have better worst case complexities for set (for example insert ).


2 Answers

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.

like image 141
PierreBdR Avatar answered Oct 04 '22 00:10

PierreBdR


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.

like image 33
Mr Fooz Avatar answered Oct 04 '22 01:10

Mr Fooz