Specializes in std :: more via std :: rel_ops

How can I specialize std::greaterwith std::rel_ops? I have something like this

#include <utility>
#include <functional>

using namespace std::rel_ops;

struct MyStruct {
    int field;
    bool operator < (const MyStruct& rhs) const {
        return field < rhs.field;
    }
};

So I need to sort the items in descending order. How can I do this using operator <, std::rel_opsand std::greater?

+4
source share
3 answers

I assume you tried to do something similar to

MyStruct ms[] = {{10}, {50}, {30}, {20}};
std::sort(std::begin(ms), std::end(ms), std::greater<MyStruct>{});

, operator> . , std::greater ADL, , ADL . std::rel_ops MyStruct. , , MyStruct, operator>.

using std::rel_ops::operator>;

, , std::rel_ops Boost.Operators .

+4

:

std::vector<MyStruct> v{...};

std::sort(v.begin(), v.end(), [](const MyStruct& lhs, const MyStruct& rhs){
    using namespace std::rel_ops;
    return lhs > rhs;
});

std::rel_ops . boost::less_than_comparable, MyStruct:

struct MyStruct 
    : boost::less_than_comparable<MyStruct> // <== adds operator>,
                                            //          operator>=, 
                                            //      and operator<=
{
    MyStruct(int i) : field(i) { }
    int field;

    bool operator<(const MyStruct& rhs) const {
        return field < rhs.field;
    }
};

-:

std::sort(v.begin(), v.end(), std::greater<MyStruct>());
+1

std :: rel_ops generate other comparisons from ==and <, so you first need to define at least<

bool operator<(const MyStruct & lhs, const MyStruct & rhs) {
    return lhs.field < rhs.field;
}

Now rel_ops generates >, so now you can use std::greaterinstd::sort

std::sort(begin(myVector), end(myVector), std::greater<MyStruct>());
0
source

Source: https://habr.com/ru/post/1611985/


All Articles