如何在不重新索引顶点的情况下调用“boost :: remove_vertex”?

问题描述 投票:1回答:1

我注意到,如果我调用boost::remove_vertex,顶点会重新编入索引,从零开始。

例如:

#include <boost/graph/adjacency_list.hpp>
#include <utility>
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
  boost::adjacency_list<> g;

  boost::add_vertex(g);
  boost::add_vertex(g);
  boost::add_vertex(g);
  boost::add_vertex(g);

  boost::remove_vertex(0, g); // remove vertex 0

  std::pair<boost::adjacency_list<>::vertex_iterator,
            boost::adjacency_list<>::vertex_iterator> vs = boost::vertices(g);

  std::copy(vs.first, vs.second,
            std::ostream_iterator<boost::adjacency_list<>::vertex_descriptor>{
              std::cout, "\n"
                });
  // expects: 1, 2 and 3
  // actual: 0, 1 and 2, I suspect re-indexing happened.
}

我想知道如何使上面的代码输出1,2和3?

c++ boost boost-graph
1个回答
2
投票

顶点索引失效的原因是VertexListS模板的顶点容器选择器(adjacency_list)的默认值。

  template <class OutEdgeListS = vecS,
        class VertexListS = vecS,
        class DirectedS = directedS,
        ...
  class adjacency_list {};

当您为remove_vertex调用adjacency_list时,VertexListSvecS,图表的所有迭代器和描述符都将失效。

为了避免使描述符无效,您可以使用listS而不是vecS作为VertexListS。如果使用listS,则不会得到隐式vertex_index,因为描述符不是合适的整数类型。相反,对于listS,您将使用不透明的顶点描述符类型(实现可以转换回列表元素引用或迭代器)。

这就是为什么你应该使用vertex_descriptor来引用一个顶点。所以你可以写

 typedef boost::adjacency_list<boost::vecS,boost::listS> graph;
 graph g;

 graph::vertex_descriptor desc1 = boost::add_vertex(g);
 boost::add_vertex(g);
 boost::add_vertex(g);
 boost::add_vertex(g);

 boost::remove_vertex(desc1, g);

 std::pair<graph::vertex_iterator,
        graph::vertex_iterator> vs = boost::vertices(g);

 std::copy(vs.first, vs.second,
        std::ostream_iterator<graph::vertex_descriptor>{
          std::cout, "\n"
            });
© www.soinside.com 2019 - 2024. All rights reserved.