C++ std::sort predicate with templates

By , last updated May 22, 2017

Sorting std::list

Sorting a std::list is almost the same as sorting a vector or a string, except with std::list the sort method is a member function. Except this difference, the std::list::sort method doesn’t accept a range, and it comes with two overloads. One without any predicate, and one with a predicate. The usage is identical to what was covered earlier.

Given a list of numbers, just call sort() with no arguments to sort by the default operator <.

std::list<int> numbers = { 0,9,1,2,8,4,6 };
numbers.sort();

The output is:

Numbers sorted: 0 1 2 4 6 8 9

The same applies to sorting a struct. For simplicity, we’ll use the car struct from before and the sortYear predicate from before. Using lambdas would be

std::list<car> cars = {
    { "Volvo", "V70", 2007, 20000.0 },
    { "Porsche", "911", 1999, 65000.0 },
    { "Ford", "Mondeo", 2010, 25000.0 },
    { "Volvo", "V90", 2016, 55000.0 }
};

// Sort by free method predicate
cars.sort(&sortYear);

// Sorting a list with a lambda as predicate
auto sortYearPredicate = [](const car & a, const car & b) -> bool
{
    return a.year < b.year; 
};

cars.sort(sortYearPredicate);

The output is:

Cars sorted in a list
1. Porsche 911 1999 (65000)
2. Volvo V70 2007 (20000)
3. Ford Mondeo 2010 (25000)
4. Volvo V90 2016 (55000)

Professional Software Developer, doing mostly C++. Connect with Kent on Twitter.