8

I have a couple questions about how to use C++ sets (std::set)

  1. Is there a way to get the union, intersection, or difference of two C++ sets? (It's pretty easy to write my own functionto do that but I wanted to know if there was a built in function for it)

  2. Can C++ sets be used as keys in a map?

timrau
  • 22,578
  • 4
  • 51
  • 64
Alex319
  • 3,818
  • 9
  • 34
  • 40

2 Answers2

18

Use the set_difference(), set_union(), set_intersection() and set_symmetric_difference() functions.

Sets and maps support any key type that can compare. By default this means the type has operator<() defined, but you can provide your own comparator. C++ sets don't have operator<() defined and therefore can't be used as keys unless you provide your own comparator.

wilhelmtell
  • 57,473
  • 20
  • 96
  • 131
  • And you probably don't want to provide your own comparator unless you can find a way to figure out which set is "less than" the other quickly -- i.e. *without* reading all of its members, which could get very slow for a large set. – quark Nov 15 '09 at 03:14
3

Anything can be used as a key in a map as long as you provide a class or function that can compare them. Here is an example.

David Brown
  • 13,336
  • 4
  • 38
  • 55