How to have a set of structs in C++

前端 未结 7 587
渐次进展
渐次进展 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:00

    struct Blah
    {
        int x;
    };
    
    bool operator<(const Blah &a, const Blah &b)
    {
        return a.x < b.x;
    }
    
    ...
    
    std::set my_set;
    

    However, I don't like overloading operator< unless it makes intuitive sense (does it really make sense to say that one Blah is "less than" another Blah?). If not, I usually provide a custom comparator function instead:

    bool compareBlahs(const Blah &a, const Blah &b)
    {
        return a.x < b.x;
    }
    
    ...
    
    std::set my_set;
    

提交回复
热议问题