How can I use a custom type as key for a map in C++?

后端 未结 3 481
Happy的楠姐
Happy的楠姐 2020-12-01 12:25

I am trying to assign a custom type as a key for std::map. Here is the type which I am using as key:

struct Foo
{
    Foo(std::string s) : foo_va         


        
3条回答
  •  借酒劲吻你
    2020-12-01 12:53

    I suspect you need

    bool operator<(const Foo& foo1) const;
    

    Note the const after the arguments, this is to make "your" (the left-hand side in the comparison) object constant.

    The reason only a single operator is needed is that it is enough to implement the required ordering. To answer the abstract question "does a have to come before b?" it is enough to know whether a is less than b.

提交回复
热议问题