Sorting a list of a custom type

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()


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.


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

Tags:

C++

Stl