E
E
EzikBro2020-06-21 00:16:30
C++ / C#
EzikBro, 2020-06-21 00:16:30

Why doesn't std::greater() work with self-written structs?

Good evening.
I have a triple structure that has a greater than operator defined:

struct triple
{
    int c, v, u;
    
    triple(int cn, int vn, int un)
    {
        c = cn, v = vn, u = un;
    }

    bool operator >(triple n)
    {
        if (c > n.c)
            return true;
        return false;
    }
};


If I try to run the following code, the program crashes with error C2678 (binary ">": no operator found that takes a left operand of type "const _Ty" (or there is no acceptable conversion)):
int main()
{
    triple a(10, 1, 2);
    triple b(20, 2, 3);
    priority_queue<triple, vector<triple>, greater<triple>> q;
    q.push(a);
    q.push(b);

    return 0;
}


If you declare an operator outside the structure with the desired signature and such an implementation, then the program crashes with a Stack overflow error:
bool operator >(const triple& a, const triple& b)
{
    return a > b;
}


And in such an implementation, the program works correctly and without errors, although in theory it is no different from the previous one:
bool operator >(const triple& a, const triple& b)
{
    if (a.c > b.c)
        return true;
    return false;
}


The question itself:
Why can't pluses compare constant expressions by reference in the same way as ordinary ones?
And how can you declare the desired comparison operator inside the structure itself so that it does not get in the way outside of its definition?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Zhilin, 2020-06-21
@EzikBro

We need const-correctness, and the absence of unnecessary copying is also important. An example of an operator defined in a class:

bool operator >(const triple& n) const
{
    return c > n.c;
}

In general, it seems that the whole class can be replaced by:
using triple = std::tuple<int, int, int>;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question