Set stl comparator function

Q9. Sets STL#9
Predict the output of the following code :

struct student{
    string name;
    float cgpa;
    student(string name, float cgpa){
        this -> name = name;
        this -> cgpa = cgpa;
    }
};

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;
    }
};

    set < student, comp > batch ;
    batch.insert(student("Wang", 8.1));
    batch.insert(student("Ming", 6.32));
    batch.insert(student("Bruce", 8.82));
    batch.insert(student("Pandora", 7.63));

    for(student i : batch)
        cout<< i.cgpa << '\t ';

8.1 8.82 6.32 7.63

8.82 6.32 7.63 8.1

8.82 6.32 8.1 7.63

8.1 8.1 6.32 8.82

How comparator works in set?

It is similar to all the other STL’s. When you are sending by reference (by using & operator) to a custom comparator it must be sent with const type. const means that it will become immutable.
bool operator () (student& x, const student& y) will give error as the first parameter is not with a const.

I want to know, how comparator works in set

The comparator in All the STLS work the same.
I would recommend you watching this video to have a better understanding.

Yes, I have seen it but I have got the doubt on comparator function working behaviour in different containers and algorithms. If you observe carefully then you’ll understand what i’m talking here. See, my point is that we implement comparator function so that it’ll change the condition to compare the two elements or objects. So, where’s the change then, it’s in implementation. Right!!

Like I said if you observe that, comparator function works,

  1. In priority_queue is quite opposite to the condition you set in the comparator function
  2. In sort() function is similar to the conditon you set in the comparator function
  3. In lower_bound and upper_bound, it’s same again but implementation is different i.e. binary search.

Like wise, I want to know how comparator function works in other containers?

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.