Making an adjacency list in C++ for a directed graph

后端 未结 5 2013
隐瞒了意图╮
隐瞒了意图╮ 2021-01-02 01:19

Hello all :) Today I am refining my skills on graph theory and data structures. I decided to do a small project in C++ because it\'s been a while since I\'ve worked in C++

5条回答
  •  我在风中等你
    2021-01-02 01:23

    My approach would be to use a hash map to store the list of nodes in the graph

    class Graph {
    private:
      unordered_map nodeList;
      ...
    }
    

    The map takes the node ID as key, and the node itself as value. This way you could search for a node in the graph in constant time.

    The node contains the adjacency list, in this case as a c++11 vector. It could also be a linked list, although for this use case I would not see a difference in efficiency. Maybe the list would be better if you would like to keep it sorted somehow.

    class Node{
        uint64_t id;     // Node ID
        vector adjList;  
    ...
    }
    

    With this approach you have to go through the adjacency list and then search the map on the ID to get the node.

    As an alternative, you could have a vector of pointers to the neighbor nodes itself. That would give you a direct access to the neighbor nodes, but then you could not use a map to keep all your nodes in the graph, and you would loose the possibility to search entries easily in your graph.

    As you can see, there is a lot of trade-off decisions you have to make when implementing a graph, all depends on your use cases.

提交回复
热议问题