C++ cyclic dependency confusion with adjacency list representation

孤街浪徒 提交于 2020-01-05 15:11:47

问题


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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/28910892/c-cyclic-dependency-confusion-with-adjacency-list-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!