std::unordered_set of pointers

std::unordered_set of pointers

本文关键字:of pointers set unordered std      更新时间:2023-10-16

我有以下结构体

struct MyClass {
    int myInt;
    std::map<int, int> myMap;
};

我想使用unordered_set<MyClass*, PointedObjHash, PointedObEq>,但我找不到一个有效的方式来声明PointedObEq

我试着

struct PointedObjHash {
    size_t operator() (MyClass* const& c) const {
        std::size_t seed = 0;
        boost::hash_combine(seed, c->myInt);
        boost::hash_combine(seed, c->myMap);
        return seed;
    }

和我希望它是好的,但我找不到一种方法来声明PointedObjEq

—EDIT—

如果declare operator==在类内调试永远不会中断,但我认为因为MyClass == MyClass*永远不会发生…

struct MyClass {
    ...
    ...
    bool operator==(MyClass* const& c) {
        return this->myInt == c->myInt & this->myMap == c->myMap;
    }

如果declare operator==在类内调试永远不会中断,但我认为因为MyClass == MyClass*永远不会发生…

unordered_set需要使用operator==(或PointedObjEq)来复查哈希函数的结果。哈希提供了近似的等式,等式函数用于剔除误报。

如果你已经测试了两次向集合添加相同的值,那么你已经测试了相等函数。当然,可以让它打印一些东西到控制台。

由于不可能定义具有两个指针操作数的operator==函数,因此必须使用PointedObjEq类。注意,它的两边都有一个MyClass const *。同样,也不需要使用指针的引用。

struct PointedObjEq {
    bool operator () ( MyClass const * lhs, MyClass const * rhs ) const {
        return lhs->myInt == rhs->myInt
            && lhs->myMap == rhs->myMap;
    }
};

应该这样做:

struct PointedObEq {
    bool operator()(MyClass const * lhs, MyClass const * rhs) const {
        return lhs->myInt == rhs->myInt && lhs->myMap == rhs->myMap;
    }
};

你的解决方案不起作用的原因是因为你有效地编写了一个机制来比较MyClassMyClass*,当你真正需要比较MyClass*MyClass*的时候。


注::我最初的答案通过const&传递了指针。仔细想想,这是一种奇怪的编码风格,所以我把它改成了按值传递指针。

typedef MyClass* PtrMyClass;
struct PointedObjCompare
{   // functor for operator==
    bool operator()(const PtrMyClass& lhs, const PtrMyClass& rhs) const
    {   
        // your code goes here
    }
};
std::unordered_set < MyClass*, PointedObjHash, PointedObjCompare > myset;