3

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
1
  • 1
    Adding the base c++ (some people don't follow the specific version tags, so the base language tag should always be added). Commented Sep 11, 2024 at 12:37

1 Answer 1

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

Great, Thanks. It worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.