c++c++20comparatorstd-ranges

How to sort descending with cpp 20 ranges projections


Say I have a Person class like this.

class Person
{
    friend std::ostream &operator<<(std::ostream &out, const Person &operand);

public:
    Person(std::string name, std::string address, int age, int height, int weight)
        : m_name(name), m_address(address), m_age(age), m_height(height), m_weight(weight)
    {
    }

public:
    std::string m_name;
    std::string m_address;
    int m_age;
    int m_height;
    int m_weight;
};

std::ostream &operator<<(std::ostream &out, const Person &operand)
{
    out << "Person [" << operand.m_name << ", " << operand.m_age << "]";
    return out;
}

Currently trying cpp 20 projections, so I can sort using projections like this.

std::ranges::sort(persons, {}, &Person::m_age);

Just curious, how about descending?

Tried the following, gives compiler error.

std::ranges::sort(persons, {}, -1 * &Person::m_age);

Also tried reverse as following. Again compiler error

std::ranges::reverse(persons, {}, &Person::m_age);

FYI used the following for compilation

g++ "-static" -o main.exe .\*.cpp -std=c++20

Solution

  • With std::ranges::sort you can specify a comparator in addition to the projection.

    The default is std::ranges::less which gives an ascending order.
    To get the opposite order (descending) you can use std::ranges::greater:

    std::ranges::sort(persons, std::ranges::greater{}, &Person::m_age);
    

    Live demo