C++ cyclic dependency confusion with adjacency lis

2019-07-30 04:14发布

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

2条回答
甜甜的少女心
2楼-- · 2019-07-30 04:45

Delay defining Hash::operator() until after defining Node and declare Node before Hash. You can have a reference to an incomplete type as long as you don't do anything with it.

class Node;

class Hash{
    public:
        size_t operator()(const Node &node) const;
};

class Node{
    public:
        int data;
        unordered_set<Node, Hash> links;
};

inline size_t Hash::operator()(const Node &node) const{
    return node.data;
}
查看更多
贪生不怕死
3楼-- · 2019-07-30 04:58

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, because unordered_set of Node expects the Node 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 the unordered_set to a pointer, preferably a smart pointer:

unordered_set<shared_ptr<Node>, Hash> links;
...
size_t Hash::operator()(const shared_ptr<Node> &node) const{
    return node->data;
}

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.

查看更多
登录 后发表回答