c++ - 类具有std::unordered_set的相同类的指针

标签 c++ class c++11 hashset stdset

我正在尝试创建一个包含指向同一类的指针的std::unordered_set的类,但是在声明该类之前无法找到准备哈希函数的方法。

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);
}



最佳答案

我假设您的意思是std::hash中的 hash::operator() (如果这样),请指定完整范围并包括 <functional> 。然后所有人都需要Vertex类的前向声明,然后是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);
}

另外,请注意,您不需要采用指针的const -ref(即Vertex const*& other),而只需采用pass it by value for primitive types即可。

关于c++ - 类具有std::unordered_set的相同类的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62738521/

相关文章:

c++ - 函数指针类型和值的部分类特化

c++ - 有没有办法在不链接到-framework ApplicationServices 的情况下运行c 或c++ 文件?

java - 覆盖错误Java,程序不会只读取两种方法

c++ - 枚举类不明确继承

C++0x 智能指针比较 : Inconsistent, 原理是什么?

c++ - TCP 数据包有时会合并(并且延迟?)

c++ - 如何编写图形程序

java - 我的数组和数组列表 java for android 有什么问题

php - 从 PHP 类回显变量

c++ - 创建此功能模板