I’m having a hard time trying to understand other people’s codes here.
I would really appreciate if someone helps me.
Let’s say there is an array of object : vpair_list and this vpair_list has a type of class of vpair. So, it would be like this:
class vpair
{
public:
int vid;
int vlabel;
};
bool operator < (const vpair& x, const vpair& y);
vpair* vpair_list;
vpair_list = new vpair[25];
..
sort(vpair_list, vpair_list+j);
What I know from that is sort() compares each element of array vpair_list and sorts them.
The thing is that I just can’t understand how that sorting works since the object vpair has two different properties.
Does the sorting work like comparing each property(vid and vlabel) or….? What I thought was the sorting was supposed to be done by comparing specific field or property (either vid or vlabel here).
But this code hasn’t got anything to do with that and seems like it just compares the whole object. Could someone tell me how that works?
Thank you in advance.
It happens exactly how you want it to happen.
By default as people have mentioned, the
<operator is used by various sort algorithms to arrange elements in ascending order of that operator. However for classes/structs there is no default way to compare them meaning you the programmer has to code it in.That is what
is. It is just a declaration to the definition of the function the programmer has provided to compare 2
vpairorder. The programmer uses his rules to decide and ultimately returnstrueorfalse. This is used to sort.So you can decide exactly how you want it to sort.
This would sort by ascending order of ID, if they are equal, It then sorts by ascending order of vlabel.