1

I know comparators for sorting ,I know that comp(x,y) should return true to get order ..,x ,....,y.. in a vector.

bool comp(int x,int y){
    return occurences[x]<occurences[y];
}

sort(data.begin(),data.end(),cmp); according to x will followed by y in vector (...x..y..)

But recently I get to know about same thing using operator overloading regarding which i have some doubts.

struct Edge{
    int u,v,weight;
    bool operator < (Edge const& other){
       return weight < other.weight;
    }
}

1) will it going to work in the same way?Like here if current edge weight

2)And which will come first ,I mean above in above format comp(x,y) return true then x will come first But what is the criteria here because it seems that we are passing only argument here in the operator overloading function. Like if we compare Edge1(weight=40) < Edge2(weight=60) then which will come first and why?

user12345
  • 11
  • 1
  • Did you write a test and debug it? – Robert Andrzejuk Jun 12 '19 at 07:22
  • The left-hand operand of your operator is `*this`, and `other` is the right-hand one. – Quentin Jun 12 '19 at 07:24
  • 3
    `bool operator<(Edge const& other){` should be `bool operator<(Edge const& other) const {`, it's not going to work without the extra `const`. It's better to declare `operator<` as a free function however. – john Jun 12 '19 at 07:29

2 Answers2

1

When declaring a member function of a class, there is an "invisible" first argument : this

So outside the class the function looks something like:

bool operator < (const Edge* this, Edge const& other)
        { return this->weight < other.weight; }

So the left (first) variable is always this and the right (second) variable is other.

Another way to look at is like Aconcagua has suggested:

An expression x < y is mapped to Edge x, y; x.operator<(y); – this is calling the operator explicitly.

For more details about operator overloading: What are the basic rules and idioms for operator overloading?

Robert Andrzejuk
  • 5,076
  • 2
  • 22
  • 31
0

If you don't give std::sort a custom comparator, then the range will be sorted by comparing elements using operator<.

Logically, there is only a single-line difference between the two versions of std::sort:

if (obj1 < obj2) {

vs

if (cmp(obj1, obj2)) {

In both instances, objects will be sorted such that for any object obj1 sorted before another object obj2, the comparison will return true.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52