How to have a set of structs in C++

前端 未结 7 610
渐次进展
渐次进展 2021-02-01 21:01

I have a struct which has a unique key. I want to insert instances of these structs into a set. I know that to do this the < operator has to be overloaded so that set can mak

7条回答
  •  南旧
    南旧 (楼主)
    2021-02-01 21:50

    This might help:

    struct foo
    {
      int key;
    };
    
    inline bool operator<(const foo& lhs, const foo& rhs)
    {
      return lhs.key < rhs.key;
    }
    

    If you are using namespaces, it is a good practice to declare the operator<() function in the same namespace.


    For the sake of completeness after your edit, and as other have pointed out, you are trying to add a foo* where a foo is expected.

    If you really want to deal with pointers, you may wrap the foo* into a smart pointer class (auto_ptr, shared_ptr, ...).

    But note that in both case, you loose the benefit of the overloaded operator< which operates on foo, not on foo*.

提交回复
热议问题