1

I've searched all over, but I can't find a built-in way to perform boolean operations between unordered_sets in c++. I've read about set_intersection, but that only works on ordered sets.

This is incredibly easy in something like Python:

a = set([1, 2, 3, 4])
b = set([2, 4])
>>> a.difference(b)
   set([1, 3])
>>> a.intersection(b)
   set([2, 4])
>>> a.union(b)
   set([1, 2, 3, 4])

I have trouble believing that between C++11 and boost, there's no clean way of doing this without writing your own functions.

Am I missing something? Is there a reason something like this doesn't exist already?

EDIT: I've read this post, but it only describes a way to write your own intersect/difference/union functions. I'm looking for something built into stl or boost.

EDIT: It may be easier to describe this way...

std::unordered_set<int> whole({1, 2, 3, 4});
std::unordered_set<int> even({2, 4});

// Why doesn't something like the following exist?
std::unordered_set<int> odd = whole.difference(even);
// Result would contain {1, 3}.

This is something that I would expect to be so frequently used that I have trouble believing it isn't built-in somewhere (or at least in boost).

Community
  • 1
  • 1
Kirk
  • 11
  • 2
  • Why can't you use `std::set` (ordered set)? What are the operations available on the elements of your set? Without ordering, set operations are at least of linear time complexity. Notice that `std::set` is often preferable to `std::unordered_set` (so you need to provide some order on the elements) – Basile Starynkevitch Nov 04 '15 at 05:55
  • @BasileStarynkevitch Set difference and intersection are linear time anyway. – Potatoswatter Nov 04 '15 at 06:03
  • @BasileStarynkevitch Why would it matter what operations are available on the elements of my set, as long as they're hashable? I would say that std::set is preferable if you care about order or memory, but in my case I value access speed over memory, and the order isn't important to me, so std::unordered_set is the best option. – Kirk Nov 04 '15 at 20:02

0 Answers0