Clayton Toste
Clayton Toste

Reputation: 61

Class with std::unordered_set of pointers of same class

I am trying to create a class that contains an std::unordered_set of pointers to the same class, but I am unable to find a way to prepare the hash function before declaring the class.

struct hash
{
   inline std::size_t operator()(Vertex const * & other);
};

struct Vertex
{
    // ...
    double x, y, z;
    std::unordered_set<Vertex *, hash> touching;
};

inline std::size_t hash::operator()(Vertex * const & other) const
{
    return ((hash<double>()(other->x))>>1)^
            ((hash<double>()(other->y))   )^
            ((hash<double>()(other->z))<<1);
}

Upvotes: 0

Views: 90

Answers (1)

JeJo
JeJo

Reputation: 32972

I assume that you meant the std::hash, in the hash::operator(), if so specify the full scope and include <functional>. Then all need a forward declaration of the Vertex class, then all fine

#include <unordered_set>
#include <functional>  // std::hash

struct Vertex;  // forward declare the `Vertex` 

struct hash
{
   std::size_t operator()(Vertex* other) const;
};

struct Vertex
{
   double x, y, z;
   std::unordered_set<Vertex*, ::hash> touching;
};

std::size_t hash::operator()(Vertex* other) const
{
   return ((std::hash<double>()(other->x)) >> 1) ^
      ((std::hash<double>()(other->y))) ^
      ((std::hash<double>()(other->z)) << 1);
}

Also, note that you do not need to take the const-ref of a pointer (i.e. Vertex const*& other), just pass it by value for primitive types.

Upvotes: 2

Related Questions