Sorting a list of a custom type

前端 未结 3 669

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<int,int>;
    list<my_type> 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<some_struct>  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()

    0 讨论(0)
  • 2020-11-30 09:33

    std::list::sort has a one-argument form, with the first argument being the comparison function.

    0 讨论(0)
  • 2020-11-30 09:37

    You can specify a custom sort predicate. In C++11 this is best done with a lambda:

    typedef std::pair<int, int> ipair;
    std::list<ipair> thelist;
    
    thelist.sort([](const ipair & a, const ipair & b) { return a.first < b.first; });
    

    In older versions of C++ you have to write an appropriate function:

    bool compFirst(const ipair & a, const ipair & b) { return a.first < b.first; }
    
    thelist.sort(compFirst);
    

    (Instead if ipair you can of course have your own data structure; just modify the comparison function accordingly to access the relevant data member.)

    Finally, if this makes sense, you can also equip your custom class with an operator<. That allows you to use the class freely in any ordered context, but be sure to understand the consequences of that.

    0 讨论(0)
提交回复
热议问题