leonel shovo
leonel shovo

Reputation: 51

operator > overloading is not working

Previously I have overloaded operator < and I have sorted a structure.

Now I am trying to overload operator > but it doesn't work (actually doesn't even compile). I need some help to find out the queries.

#include <bits/stdc++.h>
#include <algorithm>
using namespace std;
struct a
{
    int num1;
    int num2;
    bool operator > (const a& rhs) const
    {
        return  num1>rhs.num1;
    }
};

int main()
{
    a array[1000];
    for(int i=0; i<2; i++)
    {
        cin>>array[i].num1>>array[i].num2;
    }
    sort(array, array+2);
    for(int i=0; i<2; i++)
    {
        cout<<array[i].num1<<" "<<array[i].num2<<endl;
    }
}

Upvotes: 0

Views: 180

Answers (1)

Hatted Rooster
Hatted Rooster

Reputation: 36483

When looking at std::sort we can see when using the overload with 2 parameters:

1) Elements are compared using operator<

This means that if your custom type does not define operator< you will get a compiler error. You can use a custom comparator as the third parameter if you don't want to overload this operator. Alternatively you could just invert the result of your operator>:

bool operator < (const a& rhs) const
{
   return !(num1>rhs.num1);
}

Upvotes: 4

Related Questions