How can I use std::maps with user-defined types as key?

前端 未结 7 1675
灰色年华
灰色年华 2020-11-22 04:30

I\'m wondering why I can\'t use STL maps with user-defined classes. When I compile the code below, I get the following cryptic error message. What does it mean? Also, why is

7条回答
  •  醉话见心
    2020-11-22 05:07

    You don't have to define operator< for your class, actually. You can also make a comparator function object class for it, and use that to specialize std::map. To extend your example:

    struct Class1Compare
    {
       bool operator() (const Class1& lhs, const Class1& rhs) const
       {
           return lhs.id < rhs.id;
       }
    };
    
    std::map c2int;
    

    It just so happens that the default for the third template parameter of std::map is std::less, which will delegate to operator< defined for your class (and fail if there is none). But sometimes you want objects to be usable as map keys, but you do not actually have any meaningful comparison semantics, and so you don't want to confuse people by providing operator< on your class just for that. If that's the case, you can use the above trick.

    Yet another way to achieve the same is to specialize std::less:

    namespace std
    {
        template<> struct less
        {
           bool operator() (const Class1& lhs, const Class1& rhs) const
           {
               return lhs.id < rhs.id;
           }
        };
    }
    

    The advantage of this is that it will be picked by std::map "by default", and yet you do not expose operator< to client code otherwise.

提交回复
热议问题