集合中的比较器如何与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;
}

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

我没有定义运算符在重复值上返回true,那么为什么它会显示这种行为呢?

因为CCD_;小于";比较器,并以这种方式实现。也就是说,如果对于集合中的两个值xyx<yy<x都为假,则假定xy相等,因此它们是重复的。

最新更新