Reputation: 43159
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?
Upvotes: 3
Views: 416
Reputation: 254501
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.
Upvotes: 5
Reputation: 473577
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.
Upvotes: 1
Reputation: 65619
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.
Upvotes: 2