How to have a set of structs in C++

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

    In c++11 we can use a lambda expression, I used this way which is similar to what @Oliver was given.

    #include 
    #include 
    #include 
    
    struct Blah
    {
        int x;
    };
    
    
    
    int main(){
    
        auto cmp_blah = [](Blah lhs, Blah rhs) { return lhs.x < rhs.x;};
    
        std::set my_set(cmp_blah);
    
        Blah b1 = {2};
        Blah b2 = {2};
        Blah b3 = {3};
    
        my_set.insert(b1);
        my_set.insert(b2);
        my_set.insert(b3);
    
        for(auto const& bi : my_set){
            std::cout<< bi.x << std::endl;
        }
    
    }
    

    demo

提交回复
热议问题