为什么我的比较器在插入一组时会被调用两次?

Adm*_*nel 6 c++ stl set comparator

我试图了解比较器在 cpp 中如何工作。因此,当我插入 时s1,不会调用比较器运算符,这是有道理的。但是当s2插入时,比较器运算符被调用两次。为什么?当我检查时,我发现两次调用比较器的第一个参数都是s2,而第二个参数是s1。谁能向我解释一下这一点。

#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;
}
Run Code Online (Sandbox Code Playgroud)

Jul*_*pez 0

这似乎取决于实现。

如果你在 gcc 上运行你的代码,你会得到双重调用,如果你用 clang 运行它,你不会:

https://godbolt.org/z/z7xMKaqqf

(MSVC 执行两次调用,但参数已切换)

  • 这更像是评论而不是答案...... (4认同)