c++ - 带有接受 C++ 集参数的类的自定义 key_comp

标签 c++ set eigen

我一直在尝试创建一组 Vector3ds(来自 Eigen 库)。此外,该集合将从自定义类中获取 key_comp,而该自定义类恰好也带有参数。所以下面是我的代码

#include <set>
#include <Eigen/Core>

using namespace std;
using namespace Eigen;

class Vector3dNormCompareClass {
public:
        Vector3dNormCompareClass(const double prec) {
                _prec = prec;
        }
        bool operator ()(const Vector3d lhs, const Vector3d rhs) const;
private:
        double _prec;
};

bool Vector3dNormCompareClass::operator ()(const Vector3d lhs,
                const Vector3d rhs) const {    
        if (lhs.norm() < rhs.norm())
                return true;

        for (int i = 0; i < 3; ++i) {
                if (abs(lhs(i) - rhs(i)) > _prec)
                        return lhs(i) < rhs(i);
        }
        return false;
}

class Tan {    
    set<Vector3d,Vector3dNormCompareClass> _transList;
    public:
    void setTransList(double foo);    
};


void Tan::setTransList(double foo) {
    Vector3dNormCompareClass comp(foo);
    _transList(comp);    
}

在这里,_transList是类 Tan 时我要构建的集合被宣布并且Vector3dNormCompareClasskey_comp 的类这需要比较精度的参数(因为我们正在比较 double vector )。此外,就我而言,我希望能够重置 key_comp 的精度,即 Vector3dNormCompareClass ,但不幸的是,我的代码无法通过当前形式编译。任何人都可以帮助我如何定义列表,以便它可以采用自定义 key_comp及其参数(即 double prec )?

更新 因为你们中的一些人显然更关心我的 key_comp 的数学有效性,我在其中添加了一些代码:if (lhs.norm() < rhs.norm()) return true;满足定义的条件here ,我引用:

The set object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a set container can be equivalent.

因此,通过检查 (a<b) & (b>a) ,我相信我的key_comp将满足确定等效键的条件。也就是说,double prec这里现在用于订购 key ,我想让它“灵活”,意思是能够重置,也许,每次我清除后 _transList ,即 _transList.clear() .所以我的问题仍然存在,即代码不能用当前的形式编译,如果有人能帮助我解决这个问题,我将不胜感激!

最佳答案

您不能只重置比较器,因为这(很可能)也会更改内部顺序。但是,您可以使用新的比较器重置集合(并可选择插入当前值):

void Tan::setTransList(double foo) {
    Vector3dNormCompareClass comp(foo);
    set<Vector3d,Vector3dNormCompareClass> tmp(
        _transList.begin(), _transList.end(), // remove this line if you don't want to copy old entries
        comp); 
    _transList.swap(tmp);    
}

编辑:正如 Daniel 所指出的,您的比较器不满足集合的必要条件(即传递性),即您可能会得到意想不到的结果(取决于您插入值的顺序).

关于c++ - 带有接受 C++ 集参数的类的自定义 key_comp,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53745093/

相关文章:

c++ - while 循环的迭代返回奇怪的值

c++ - 是否可以在 C++ 中声明 operator= private 并同时由编译器合成

c++ - 指向存储在结构中的数组的指针在哪里?

C++:需要索引集

c++ - 使用 EIGEN_MATRIXBASE_PLUGIN 访问 Eigen 中的模板值

C++ --- 错误 C2664 : 'int scanf(const char *,...)' : cannot convert argument 1 from 'int' to 'const char *'

swift - Xcode 9.4.1 Swift 4 - 将非原始集与包含 Int 的原始集进行比较

matrix - Transform::linear() 在 Eigen 库中返回什么?

c++ - 如何使用特征库计算曼哈顿距离?