c++ - 集合中的比较器如何与 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,那么它为什么会显示这种行为呢?
因为 astd::set
旨在与“小于”比较器一起使用,并且以这种方式实现。也就是说,如果对于两个值x
和y
集合中的x<y
和y<x
都是假的,那么x
和y
被假定为相等,因此它们是重复的。
推荐阅读
- java - Java中的静态变量和方法
- mapbox - 如何将自定义样式的 makis 与 Mapbox Studio 中的 poi-label 关联?
- java - 如何指定这些 VM 参数?
- c++ - 调用重载赋值函数时向量未正确重新初始化
- javascript - React componentDidMount未触发且未更新电子应用程序中的状态
- azure - Azure Devops 自定义扩展和当前发布上下文
- ffmpeg - 如何从透明图像创建透明视频?
- amazon-web-services - 使用 SAM 将 VPC 端点附加到 PRIVATE Rest API
- pyspark - 将 Pyspark 数据框转换为具有实际值的列表
- ios - 跳过代码中的 if - then 控制流在警报后运行