简体   繁体   中英

On-the-fly calculation of edges in Boost Graph Library possible?

In my application I have some kind of graph where every node/vertex can be connected to each other but actual connection is determined at runtime.

Of course this is trivial to implement by iterating over all existing vertices and connecting them to the last one I've added to the graph and using a filtered graph at runtime to decide of the connection still persists.

Purpose is to use BFS or DFS or other algorithms provided by BGL.

Is there any other approach to get that task done more efficiently? By example: Adding all(!) vertices at initialization and having some kind of callback which checks for an edge at runtime?

That's what how I tried to solve it but that one doesn't work:

#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/graph_utility.hpp>
struct VD { };
struct ED { };

struct Graph : boost::adjacency_matrix<boost::directedS, VD, ED>
{
    Graph() : boost::adjacency_matrix<boost::directedS, VD, ED>(4) { }
    //=================================================================
    // Functions required by the AdjacencyMatrix concept
    template <typename D, typename VP, typename EP, typename GP, typename A>
    std::pair<typename adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor, bool>
    edge(typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor u,
        typename adjacency_matrix<D,VP,EP,GP,A>::vertex_descriptor v,
        const adjacency_matrix<D,VP,EP,GP,A>& g)
    {
        // Connect vertex 1 and 2
        bool exists = (u == 1 && v == 2);

        typename boost::adjacency_matrix<D,VP,EP,GP,A>::edge_descriptor
            e(exists, u, v, boost::detail::get_edge_property(g.get_edge(u,v)));

        return std::make_pair(e, exists);
    }
};

int main() {
    Graph g;
    print_graph(g);

    std::vector<int> component(num_vertices(g));
    int num = boost::connected_components(g, &component[0]);
}

Any pointers would be appreciated!

From BGL concepts :

The heart of the Boost Graph Library (BGL) is the interface, or concepts (in the parlance of generic programming), that define how a graph can be examined and manipulated in a data-structure neutral fashion. In fact, the BGL interface need not even be implemented using a data-structure, as for some problems it is easier or more efficient to define a graph implicitly based on some functions.

There's no standard model implementation, but the docs contain an example in Chapter 19: Graph Adaptors

It shows the grid_graph adaptor, which might match your use case pretty closely. If not, it should give you good ideas about how to create implicit graph models according to the concept requirements.

[2]:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM