Click here to Skip to main content
15,029,771 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I was reading Minimum spanning tree - Kruskal with Disjoint Set Union - Competitive Programming Algorithms[^] and I am confused in below operator overloading part used in above implementation,here how we can sort without defining the comparator.

How is sorting taking Place over two structure without defining any comparator,how compiler get to know on what basis it has two sort?
When we are going to use when e1<e2 then who will call the operator overloaded <pre>+</pre>that is e1 or e2.

suppose the default comparator of STL sort using something like this
<pre> e1<e2 </pre> (e1 and e2 are of Edge type) then how are parameters passed to `bool operator<(Edge const& other)` inside struct.

What I have tried:

C++
struct Edge {
    int u, v, weight;
    bool operator<(Edge const& other) {
        return weight < other.weight;
    }
};
vector<Edge> edges;
sort(edges.begin(), edges.end());
Posted
Updated 8-Mar-19 11:51am
v2

The definition of the operator < allows the sort method to compare two Edge elements. The sort call takes the elements of the vector from first to last, and uses the overloaded comparator as defined in the struct, to decide which order they should be saved in. Because the less than operator is defined for the Edge type, that is the method that will be used when sort does something like:
C++
if (elem1 < elem2)
{
    // ...
}
   
Comments
CPallini 8-Mar-19 17:41pm
   
5.
Richard already gave you the correct answer.

As an addendum, looking at the documentation std::sort - cppreference.com[^], note the first overload of std::sort is used.

Moreover, reading this article: "Sorting a vector of custom objects in C++"[^], could be helpful.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900