首页 > 解决方案 > 集合中的比较器如何与 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重复值,那么它为什么会显示这种行为呢?

标签: c++setfunctor

解决方案


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

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


推荐阅读