问题
From what I can gather of how to use BGL in order to invoke a DFS of a graph from a known root node I need to do something along the lines of
class MyVisitor : public boost::default_dfs_visitor
{
public:
void discover_vertex(MyVertex v, const MyGraph& g) const
{
cerr << v << endl;
return;
}
};
void bfsMethod(Graph g, int rootNodeId)
{
boost::undirected_dfs(g, vertex(rootNodeId,g), boost::visitor(vis));
}
Now I am not sure how I alter this so that std::vector
of vertexId's (or pointers) is built as the DFS visits all vertices in the graph in a similar way to how the minimum spanning tree algorithm can be used e.g.
std::vector < JPEdge > spanning_tree;
kruskal_minimum_spanning_tree(g, std::back_inserter(spanning_tree));
回答1:
The vector must be a member of your visitor. In the discover_vertex
function, just push the discovered element into the vector.
class MyVisitor : public boost::default_dfs_visitor
{
public:
void discover_vertex(MyVertex v, const MyGraph& g) const
{
cerr << v << endl;
vv.push_back(v);
return;
}
vector<MyVertex> GetVector() const {return vv; }
private:
vector<MyVertex> vv;
};
void bfsMethod(Graph g, int rootNodeId)
{
MyVisitor vis;
boost::undirected_dfs(g, vertex(rootNodeId,g), vis);
vector<MyVertex> vctr = vis.GetVector();
}
来源:https://stackoverflow.com/questions/10189967/c-boost-graph-library-building-a-vector-of-vertices-visited-in-an-undirected