1

我要存储一个std::set对象Point3D,我的比较函数定义如下(字典序):

bool operator<(const Point3D &Pt1, const Point3D &Pt2)
{
    const double tol = 1e-5;

    if(fabs(Pt1.x() - Pt2.x()) > tol)
    {
        return Pt1.x() < Pt2.x();
    }    
    else if(fabs(Pt1.y() - Pt2.y()) > tol)
    {
        return Pt1.y() < Pt2.y();
    }
    else if(fabs(Pt1.z() - Pt2.z()) > tol)
    {
        return Pt1.z() < Pt2.z();
    }
    else
    {
        return false;
    }
}

在某些情况下set包含相同的点,我认为问题来自比较功能,但我没有找到确切的问题。任何帮助,将不胜感激!

4

1 回答 1

7

您的容差概念没有正确建立严格的弱排序,因为它不是传递的。举个例子,想象一下公差是1。现在考虑:

a = 1
b = 2
c = 3

这里:!(a<b)!(b<c),但是a<c。这明显违反了严格弱排序的传递性要求。

如果要实现具有容差但也是严格弱排序的比较,则必须以一致的方式(例如 、 、 等)对每个值进行1.5 => 2舍入,然后比较舍入后的值。0.75 => 12.3 => 2

这样做似乎毫无意义,因为double我们已经这样做了,但要尽可能精确。当你发现它时,你仍然会得到奇怪的行为1.4999999... != 1.5

您应该按如下方式编写比较器,并放弃容差概念:

bool operator<(const Point3D &Pt1, const Point3D &Pt2)
{
    //This can be replaced with a member/free function if it is used elsewhere
    auto as_tie = [](Point3D const &Pt) {
        //assumes the member functions return references
        //to the internal `Point3D` values.
        return std::tie(Pt.x(), Pt.y(), Pt.z());
    };
    return as_tie(Pt1) < as_tie(Pt2);
}

如果您绝对必须有容差,请在将值放入 时立即舍入Point3D,或在比较之前立即舍入值(取决于系统中的其他要求)。

于 2014-06-09T11:05:42.110 回答