Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #ifndef GRAPHTOGRAPHVIZ_H_
- #define GRAPHTOGRAPHVIZ_H_
- #include <lemon/list_graph.h>
- #include <unordered_map>
- using namespace lemon;
- using namespace std;
- /* USAGE:
- * ListDigraph::NodeMap<unordered_map<string, string>> nodeAttribs(g);
- * ListDigraph::ArcMap<unordered_map<string, string>> arcAttribs(g);
- * nodeAttribs[node]["label"] = "node_label";
- * string dot = graphToGraphviz(g, &nodeAttribs, &arcAttribs, "hello");
- */
- template<class Map>
- 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 Graph,
- class NodeAttribs = ListDigraph::NodeMap<std::unordered_map<string, string>>,
- class ArcAttribs = ListDigraph::ArcMap<std::unordered_map<string, string>>
- >
- string graphToGraphviz(Graph &graph,
- NodeAttribs *nattribs = NULL,
- ArcAttribs *aattribs = NULL,
- string name = "")
- {
- typedef typename Graph::template NodeMap<string> 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*>( &(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);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement