Sorting a list of a custom type

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.

Leave a Comment