Sorry for my inexperience with C++, but I spent quiet some time with solving a cyclic dependency issue and hence posing this.
I am trying to represent a Adjacency List in C++.
I have struct Node
,
struct Node{
int data;
unordered_set<Node, Hash> links;
bool operator == (Node const& other) const{
return (data == other.data);
}
Node(){
}
Node(int data){
this->data = data;
}
};
and I have my Hash
functor
struct Hash {
size_t operator()(const Node &node) const {
return node.data;
};
};
I noticed that Hash
uses Node
and Node
uses Hash
If for the purpose of this exercise I want to declare everything in a single file, which one should I declare first.
I tried forward declaration of both Hash
and Node
with defining either of them first, but none of them compiled.
PS: This is not homework, I'm trying to solve graph algorithm puzzles online
Delay defining
Hash::operator()
until after definingNode
and declareNode
beforeHash
. You can have a reference to an incomplete type as long as you don't do anything with it.Resolving the syntax by moving the implementation of hash to a point after the
Node
is fully defined is insufficient. No matter what the order is, you would not be able to compile it, becauseunordered_set
ofNode
expects theNode
to be a complete type, i.e. the type needs to be fully defined.In addition to splitting out the definition of
Hash::operator()
you need to change the first type parameter of theunordered_set
to a pointer, preferably a smart pointer:A regular pointer would also work, but then you would have to manage memory for your nodes separately - e.g. by placing all nodes in a vector.