User defined class as STL set member data type

I have a simple question. In the STL container class "set", can I use my own class as the member data type? Although the template definition of the "set" class obviously permits any data type, what worries me is that "set" has to remove duplicate, or equal members. If my class doesn't have an overloaded "==" operator, then it seems that the set class cannot judge whether two members are duplicate, and may lead to errors. Is this true? I have already supplied a comparison class to replace less<Key> for the set class, but haven't supplied an "==" replacement.
The std::sets use the operator<() if provided by the type, or a comparison type provided as second template parameter. If you already wrote this class, which is supposed to have an operator()() that returns true if the first parameter < the second parameter, then the set can find duplicates without problem (somehow).
I have tried compiling my program and found what you said is correct.
I guess the set class may find duplicates using the "less" function like this:
if a<b and b<a both return "false", then a=b, duplicate.
But I can't rule out (given my lack of advanced knowledge) that the set class actually examines the raw memory content of the two classes, and decides whether they are equal.
Which of the two possibilities make more sense to you? Thanks in advance.
Take a look at the documentation for set.
http://cplusplus.com/reference/stl/set/

Since it uses std::less by default, it seems to me that complex user defined types could be equivalent but not equal. Set will not perform a memory compare. If you have a class with many attributes how will your operator< work? Which attributes are compared to determine if one object is less than another? Think about it. The set is sorting elements as you insert them using whatever functor it is instructed to use. The set is only as smart as the functor that is specified.
I can guarantee you that set will not examine the raw memory of your class.

Consider using boost::tie:

1
2
3
4
5
6
7
8
struct Foo {
    int x;
    float y;
    char z;

    bool operator<( const Foo& rhs ) const
        { return boost::tie( x, y, z ) < boost::tie( rhs.x, rhs.y, rhs.z ); }
};


Topic archived. No new replies allowed.