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



我注意到,如果我调用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?

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

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

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

为避免描述符无效,您可以使用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"
});

最新更新