Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading