3

In C++, the std::set::insert() only inserts a value if there is not already one with the same 'value'. By the same, does this mean operator== or does it mean one for which operator< is false for either ordering, or does it mean something else?

Doug T.
  • 64,223
  • 27
  • 138
  • 202
WilliamKF
  • 41,123
  • 68
  • 193
  • 295

3 Answers3

5

does it mean one for which operator< is false for either ordering?

Yes, if the set uses the default comparator and compares keys using <. More generally, in an ordered container with comparator Compare, two keys k1 and k2 are regarded as equivalent if !Compare(k1,k2) && !Compare(k2,k1).

Keys are not required to implement operator== or anything else; they are just required to be comparable using the container's comparator to give a strict weak ordering.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
2

std::set has a template argument called `Compare' as in this signature:

template < class Key, class Compare = less<Key>,
       class Allocator = allocator<Key> > class set;

Compare is used to determine the ordering between elements. Here, the default less<Key> uses the < operator to compare two keys.

If it helps, you can think of a set as just a std::map with meaningless values, ie a std::set<int> can be thought of as a std::map<int, int> where the values are meaningless.

Doug T.
  • 64,223
  • 27
  • 138
  • 202
1

The only comparison that set is allowed to perform on T is via the functor type it was given to do comparisons as part of the template. Thus, that's how it defines equivalence.

For every value in the set, the comparison must evaluate to true for one of the two ordering between that value and the new one. If it's false both ways for any value, then it won't be stored.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982