DFS in boost::graph with changing the graphs content

白昼怎懂夜的黑 提交于 2019-12-05 08:44:14

Have a look at how Boost implements connected_components. In order to store the component id the following visitor is used:

// 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;
};

The idea is that a property map is passed to the constructor of the visitor, and is later used to update the data. Relating to your example, the vertex_visitor could be rewritten in the following way:

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);
  }
};

Instantiation of this visitor is a bit convoluted because we need to specify the property map type explicitly:

typedef boost::property_map<graph_t, int vertex::*>::type NumbersProperty;
vertex_visitor<NumbersProperty> vis(boost::get(&vertex::number, g));

As per the last part of the question, mutation of graph structure (i.e. addition or deletion of vertices and edges) invalidates interators, so this would break the DFS algorithm. I think this is precisely the reason why the graph is passed by const-reference.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!