我将我的问题简化为这样。我可以创建一个具有模板类型本身的无序集的类吗?具体来说,例如一个 Square 具有指向一组无序邻居的指针。我在尝试将哈希函数与类本身集成时陷入困境。 这是我的代码:
#include <iostream>
#include <unordered_set>
#define SIZE 200
#define MASTER 0
class Square;
namespace std{
template<>
struct hash<Square> {
std::size_t operator () (Square const &v) const
{
return v.r;
}
};
}
class Square{
public:
int c1, c2;
int r;
std::unordered_set<Square> *neigh;
Square() {
neigh = new std::unordered_set<Square>();
}
~Square(){
delete neigh;
}
bool operator==(const Square& second) {
return this->r == second.r
&& this->c1 ==second.c1
&& this->c2 == second.c2;
}
};
int main(int argc, char *argv[]) {
Square sq;
Square tt;
sq.neigh->insert(tt);
}
我尝试使用 g++ 和 FLAGS = --std=c++17 -Wall -Wextra -Wno-unused-parameter -Wno-unused-variable -ggdb 进行编译。收到的错误是巨大的,开头为:
test.cpp: In member function ‘std::size_t std::hash<Square>::operator()(const Square&) const’:
test.cpp:15:20: error: invalid use of incomplete type ‘const class Square’
15 | return v.x;
我不知道处理这种情况的正确方法是什么。请考虑到这是我所需要的简化代码版本,因此我确实需要一个邻居字段。
最佳答案
要解决您所询问的问题,只需声明 std::hash<Square>::operator()
之前Square
定义,但不实现它:
namespace std{
template<>
struct hash<Square> {
std::size_t operator() (Square const &) const;
};
}
然后在Square
之后定义,定义std::hash<Square>::operator()
:
namespace std {
std::size_t hash<Square>::operator() (Square const& v) const
{
// return calculation
}
}
您的 insert
有问题也。您复制带有指针的对象,然后销毁同一个指针两次。要解决这个问题,请使用 std::unique_ptr<std::unordered_set<Square>>
这很有帮助,因为如果您尝试复制它,您会收到编译错误。
class Square{
public:
std::unique_ptr<std::unordered_set<Square>> neigh;
Square() : neigh{std::make_unique<std::unordered_set<Square>>()} {}
// no destructor needed
bool operator==(const Square& second) const { // should be const
// ...
}
};
然后你必须move
物体到位:
sq.neigh->insert(std::move(tt));
或emplace
他们:
sq.neigh->emplace(...constructor arguments...);
关于c++ - 具有自身无序集合的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65795607/