Why is my comparator called twice when inserting it a set?

Viewed 107

I was trying to see how a comparator works in cpp. So when I am inserting s1, the comparator operator is not called, which makes sense. But when s2 is being inserted the comparator operator was called twice. Why? When I checked, I found that both times when it was being called first arg to comparator was s2, while second arg was s1. Can anyone explain me this.

#include <set>
#include <iostream>
#include <string>

using std::string;

// Student Class
class student {
public:
    // To store Name and Roll Number
    string name;
    int rollnum;

    // Overloaded Constructor
    student(string name, int rollnum)
    {
        this->name = name;
        this->rollnum = rollnum;
    }
};

// Comparator Class to compare 2 objects
class studentcompare {
public:
    // Comparator function
    bool operator()(const student& a,
                    const student& b) const
    {
        std::cout << a.name << "::" << b.name << std::endl;
        return a.name < b.name;
    }
};

// Driver Code
int main()
{
    // Object of class student
    student s1("Raj", 23);
    student s2("Prerna", 24);

    std::set<student, studentcompare> s;
    s.insert(s1);
    s.insert(s2);
    return 0;
}
1 Answers

That seem to be implementation dependent.

If you run your code on gcc, you get the double call, and if you run it with clang, you do not:

https://godbolt.org/z/z7xMKaqqf

(and MSVC does two calls, but with the arguments switched)

Related