How to have a set of structs in C++

前端 未结 7 499
渐次进展
渐次进展 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 22:06

    You can overload the operator < inside the class also as,

    struct foo 
    {
      int key;
      bool operator < (const foo &other) const { return key < other.key; }
    };
    

    In your question, if you want to use set bar; as declaration then, you should insert value as,

    bar.insert(*test);
    

    But that won't be a good idea, as you are making redundant copy.

提交回复
热议问题