Sets STL quiz Q9 doubt

Not clear understanding of program.

I am not able to clearly understand what is happening in program and how is the comparison being made. Please elaborate on how it is being done. I got the answer as correct just by luck.

@rahul.maheshmaheshwari

struct comp{
bool operator () (const student& x, student y) {
if ( x.name == "Wang" )
            return 1;
if ( y.name == "Wang" )
            return 0;    
 return x.name < y.name;
    }
};

Lets analyse this compare function line by line
We get two students, x and y.

First condition:
if ( x.name == "Wang" ) return 1;
This means, that if x’s name == “Wang” x should be placed before y.

If first condition is not true, then second condition will be checked
if ( y.name == "Wang" ) return 0;
This means, that if y’s name == “Wang” y should be placed before x.

For all remaining cases, we return
return x.name < y.name;
This means that the remaining elements are sorted lexicographically.

1 Like

Thanks a lot for the beautiful and clear explanation. Thanks a lot.

1 Like

Please mark the doubt as resolved :slight_smile:

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.