#ifndef GRAPHTOGRAPHVIZ_H_ #define GRAPHTOGRAPHVIZ_H_ #include #include using namespace lemon; using namespace std; /* USAGE: * ListDigraph::NodeMap> nodeAttribs(g); * ListDigraph::ArcMap> arcAttribs(g); * nodeAttribs[node]["label"] = "node_label"; * string dot = graphToGraphviz(g, &nodeAttribs, &arcAttribs, "hello"); */ template string getAttribs(Map &map){ string attribs = ""; for (const auto &el : map){ if (el.second != "") attribs += "\"" + el.first + "\"=\"" + el.second + "\","; } if (attribs != "") attribs = " [" + attribs + "]"; return attribs; } template>, class ArcAttribs = ListDigraph::ArcMap> > string graphToGraphviz(Graph &graph, NodeAttribs *nattribs = NULL, ArcAttribs *aattribs = NULL, string name = "") { typedef typename Graph::template NodeMap NodeMap; typedef typename Graph::NodeIt NodeIterator; typedef typename Graph::ArcIt ArcIterator; NodeMap labels(graph); ostringstream layout; layout << "strict digraph \""+name+"\" {\n"; // prepare labels for (NodeIterator node(graph); node != INVALID; ++node){ string label = ""; if (nattribs != NULL) label = (*nattribs)[node]["label"]; if (label == "") label = static_cast( &(ostringstream() << graph.id(node)) )->str(); label = "\"" + label + "\""; labels[node] = label; } // initialize nodes for (NodeIterator node(graph); node != INVALID; ++node){ layout << labels[node]; if (nattribs != NULL) layout << getAttribs((*nattribs)[node]); layout << ";" << std::endl; } // initialize arcs for (ArcIterator arc(graph); arc != INVALID; ++arc){ layout << labels[graph.source(arc)] << "->" << labels[graph.target(arc)]; if (aattribs != NULL) layout << getAttribs((*aattribs)[arc]); layout << ";" << std::endl; } layout << "}"; return layout.str(); } #endif /* GRAPHTOGRAPHVIZ_H_ */ int main () { lemon::ListDigraph g; graphToGraphviz(g); }