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

前端 未结 7 1774
灰色年华
灰色年华 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:11

    You need to define operator < for the Class1.

    Map needs to compare the values using operator < and hence you need to provide the same when user defined class are used as key.

    class Class1
    {
    public:
        Class1(int id);
    
        bool operator <(const Class1& rhs) const
        {
            return id < rhs.id;
        }
    private:
        int id;
    };
    

提交回复
热议问题