std::为2D点设置自定义比较器
std::set custom comparator for 2D points
我需要一个不重复的2D点列表,所以我使用带有自定义比较函数的std::set
。我使用的函数在插入点后会出现问题,因为有时std::find
找不到已经插入的点。
const double tolerance = 0.1;
struct MyPoint2D
{
MyPoint2D(double x, double y) : _x(x), _y(y) {}
double _x, _y;
};
auto compMyPoint2D = [&](const MyPoint2D& pointA, const MyPoint2D& pointB) -> bool
{
if (pointA._x < pointB._x - tolerance) return true;
if (pointA._x > pointB._x + tolerance) return false;
if (pointA._y < pointB._y - tolerance) return true;
return false;
};
std::set<MyPoint2D, decltype(compMyPoint2D)> orderedMyPoints(compMyPoint2D);
MyPoint2D pointA(0.66,1.14);
MyPoint2D pointB(0.75, 0.0);
MyPoint2D pointC(0.57,1.19);
orderedMyPoints.insert(pointA);
orderedMyPoints.insert(pointB);
orderedMyPoints.insert(pointC);
if (orderedMyPoints.find(pointC)==orderedMyPoints.end())
{
std::cout << "Not found" << std::endl;
orderedMyPoints.insert(pointC);
if (orderedMyPoints.find(pointC)==orderedMyPoints.end())
std::cout << "Still not found" << std::endl;
}
在插入std::set
之前,我是否需要对2d点进行预排序,或者有更好的2d点比较函数?
在插入所有点之后,我需要使用std::find
来获得最终的点索引。
我在Microsoft Visual Studio 2010上使用本机C++。
您的比较函数错误。去掉+-公差。当试图确定浮点值之间的绝对顺序时,这是没有用的。例如,它不强制等价的传递性。也就是说,如果A == B
(即f(A, B)
和f(B, A)
都为假)和B == C
,那么当您在其中进行公差调整时,A == C
不一定是这样。
只需这样做:
if (pointA._x < pointB._x) return true;
if (pointA._x > pointB._x) return false;
if (pointA._y < pointB._y) return true;
return false;
首先,除非你有理由不这样做,否则最好只为你的类定义operator<
,这意味着在使用std::set
等时可以减少键入,也意味着你可以使用中缀<
。其次,正如Benjamin所指出的,不应该有tolerance
。第三,你可以简化比较的逻辑。
你应该有这样的东西:
bool operator<(const MyPoint2D& lhs, const MyPoint2D& rhs)
{
return lhs._x < rhs._x || (lhs._x == rhs._x && lhs._y < rhs._y);
}
然后您可以使用std::set<MyPoint2D>
。
相关文章:
- std::设置自定义比较器
- 带自定义比较器的最小优先级队列
- 优先级队列自定义比较器
- 什么是自定义比较器以及如何在 C++ 的排序函数中使用它?
- 没有默认构造函数作为模板参数的自定义比较器
- 使用迭代器的自定义比较器函数
- Cython中带有自定义比较器的优先级队列
- gtest 期望无序元素与自定义比较器/匹配器一起使用
- 为什么在类或结构中传递自定义比较器函数?
- 在priority_queue中使用默认容器但自定义比较器
- 是否有任何统一的方法可以在 c++ 中创建自定义比较器?
- C++ priority_queue与自定义比较器并删除任何项目
- 如何在 C++11 中将 std::max 与自定义比较器一起使用?
- 通过函数指针对类内的 STL SET 使用自定义比较器
- 基于对象的两个属性的自定义比较器会引发异常
- 如何使用自定义比较器初始化类数据成员,该成员是 std::set
- 标准::set_intersection 带自定义比较器
- 使用自定义比较器C++映射,不插入所有元素
- 优先队列的自定义比较器
- C++ STL . 自定义比较器如何工作?