集合中的比较器如何与 C++ 中的仿函数一起工作?

How does comparator in a set works with functor in C++?

这里有一个简单的程序来证明我的观点:

#include <iostream>
#include <set>
class comparator
{
public:
  bool operator()(int* a, int* b){return *a < *b;}
};
int main()
{
  std::set<int*> v1{new int{1}, new int{1}, new int{2}, new int{2}};
  std::set<int*, comparator> v2{new int{1}, new int{1}, new int{2}, new int{2}};
  std::cout << v1.size() << std::endl; // 4
  std::cout << v2.size() << std::endl; // 2
  return 0;
}

在使用仿函数之前,集合通过整数地址删除重复元素。但是,在包含函子之后,它会根据值进行删除。问题是在仿函数中我没有将运算符定义为 return true 重复值,那么为什么它会显示这种行为?

I didn't define the operator to return true on duplicate values, so why would it show this behavior?

因为 std::set 旨在与“小于”比较器一起使用,并且它是以这种方式实现的。也就是说,如果集合中的两个值 xy x<yy<x 都为假,则假定 xy相等,因此它们是重复的。