How Can I Read in a Graph to an Adjacency Matrix In the Boost Graph Library?

  adjacency-matrix, boost, boost-graph, c++, graph

In the boost graph library, there are two popular functions to read in graphs from a file:
boost::read_graphviz(), and boost::read_graphml(), for the GraphViz and the GraphML format, respectively.

Now both read generically to any type of boost::adjacency_list<...>, as they are derived from the Mutable Graph concept:

#include <string>
#include <fstream>

#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/adjacency_matrix.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/graphml.hpp>
#include <boost/graph/graph_traits.hpp>

template <typename GraphType>
GraphType load(std::string filename, std::string format) {

    GraphType g(0);

    std::ifstream t(filename.c_str());
    boost::dynamic_property dp(boost::ignore_other_properties);

    if (format == "graphml")
        boost::read_graphml(t, g, dp);
    else
        boost::read_graphviz(t, g, dp);

    return g;
}

If you were to test

load<boost::adjacency_matrix<boost::undirectedS> >("my_file.gv", "graphviz");

you might get something like

Assertion failed: (false), function add_vertex, file /usr/local/include/boost/graph/adjacency_matrix.hpp, line 966.
Abort trap: 6

So how can I include the possibility to read to a boost::adjacency_matrix<...>, preferably without having to copy the graph from an intermediate adjacency list, as explained in this SO post (the graph may be really large).

What I don’t understand is, that for copying, the (copy target) graph apparently also has to be a Mutable Graph, so how can we then copy to an adjacency matrix? And not read into one?

Thanks for any help!

Note

The boost/graph/graphml.hpp library is not header-only and needs to be linked against, for example by appending -lboost_graph when compiling/linking directly from the CLI, as in

g++ -lboost_graph my_file.cc

Source: Windows Questions C++

LEAVE A COMMENT