[英]DFS in boost::graph with changing the graphs content
最小的例子:
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/depth_first_search.hpp>
struct vertex
{
int number;
};
struct edge {};
typedef boost::adjacency_list<boost::listS, boost::vecS, boost::directedS, vertex, edge> graph_t;
typedef boost::graph_traits<graph_t>::vertex_descriptor vertex_t;
typedef boost::graph_traits<graph_t>::edge_descriptor edge_t;
struct vertex_visitor : public boost::default_dfs_visitor
{
void discover_vertex(vertex_t v, graph_t& g)
{
g[v].number = 42;
}
};
int main()
{
graph_t g;
vertex_t v1 = boost::add_vertex(g);
vertex_t v2 = boost::add_vertex(g);
boost::add_edge(v1, v2, g);
vertex_visitor vis;
boost::depth_first_search(g, boost::visitor(vis));
return 0;
}
它不起作用,因為圖形需要在vertex_visitor::discover_vertex()
作為const
引用。
有沒有比編寫我自己的DFS算法(或使用const_cast
)更好的方法來做我想做的事情? 此外,您的解決方案是否允許在發現頂點時添加/刪除邊和頂點?
看看Boost如何實現connected_components 。 為了存儲組件ID,使用以下訪問者:
// This visitor is used both in the connected_components algorithm
// and in the kosaraju strong components algorithm during the
// second DFS traversal.
template <class ComponentsMap>
class components_recorder : public dfs_visitor<>
{
typedef typename property_traits<ComponentsMap>::value_type comp_type;
public:
components_recorder(ComponentsMap c,
comp_type& c_count)
: m_component(c), m_count(c_count) {}
template <class Vertex, class Graph>
void start_vertex(Vertex, Graph&) {
if (m_count == (std::numeric_limits<comp_type>::max)())
m_count = 0; // start counting components at zero
else
++m_count;
}
template <class Vertex, class Graph>
void discover_vertex(Vertex u, Graph&) {
put(m_component, u, m_count);
}
protected:
ComponentsMap m_component;
comp_type& m_count;
};
我們的想法是將屬性映射傳遞給訪問者的構造函數,稍后用於更新數據。 關於您的示例,可以通過以下方式重寫vertex_visitor
:
template <class PropertyMap>
struct vertex_visitor : public boost::dfs_visitor<>
{
PropertyMap m_pmap;
vertex_visitor(PropertyMap pmap) : m_pmap(pmap) {}
template <class Vertex, class Graph>
void discover_vertex(Vertex v, const Graph& g)
{
boost::put(m_pmap, v, 42);
}
};
這個訪問者的實例化有點令人費解,因為我們需要明確指定屬性映射類型:
typedef boost::property_map<graph_t, int vertex::*>::type NumbersProperty;
vertex_visitor<NumbersProperty> vis(boost::get(&vertex::number, g));
根據問題的最后部分,圖結構的變異(即頂點和邊的添加或刪除)使整數器無效,因此這將破壞DFS算法。 我認為這正是圖表通過const-reference傳遞的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.