[英]how to call “boost::remove_vertex” without re-indexing the vertices?
我注意到,如果我调用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 {};
当您为具有VertexListS
作为vecS
adjacency_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"
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.