[英]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.