Sorting a list of a custom type

前端 未结 3 672

I want to have a stl list of objects where each object contains two int\'s. Afterwards I want to sort the list with stl::sort after the value of th

3条回答
  •  感情败类
    2020-11-30 09:29

    You can do something like this:

    typedef std::pair;
    list test_list;
    
    bool my_compare (my_type a, my_type b)
    {
        return a.first < b.first;
    }
    
    test_list.sort(my_compare);
    

    If the type was a struct or class it would work something like this:

    struct some_struct{
        int first;
        int second;
    };
    
    list  test_list;
    
    bool my_compare (const some_struct& a,const some_struct& b)
    {
        return a.first < b.first;
    }
    
    test_list.sort(my_compare);
    

    Or alternatively you can define operator < for your struct and just call test_list.sort()

提交回复
热议问题