首页 文章

使用c boost库从图形中删除顶点及其所有邻居

提问于
浏览
2

我想从图G中删除与邻居的顶点w .

我的代码:

// remove all neighbours
MyGraph::adjacency_iterator n_iter, n_end;
for (tr1::tie(n_iter, n_end) = boost::adjacent_vertices (*w, G1); n_iter != n_end; ++n_iter)
{
    boost::remove_vertex(*n_iter, G1);
}

MyGraph::vertex_iterator vertex_iter, vertex_end;
Vertex vertex_w = G[*w];

// remove vertex himself
for (tr1::tie(vertex_iter, vertex_end) = boost::vertices(G1);vertex_iter != vertex_end; ++vertex_iter)
{
    Vertex vertex = G1[*vertex_iter];
    if (vertex.p_index == vertex_w.p_index)
    {
        boost::remove_vertex(*vertex_iter, G1);
        break;
    }
}

我试图迭代相邻的顶点并删除它们 . 之后,我试图删除顶点w .

但是在启动程序时出现了一些异常和错误 .

有人提示我从图表中移除所有邻居并使用Vertex w吗?

Update: 现在我明白为什么上面的代码赢了't work (I' m使用VertexList = vecS) . 我现在尝试将顶点标记为"removed"并想要删除所有边 .

图形:

0     1
o-----o
|     |
|     |
o-----o
2     3

码:

typedef boost::adjacency_list<boost::listS, boost::vecS, boost::undirectedS, Vertex, Edge> MyGraph;
[...]
// *w is Vertex "1"
boost::graph_traits<MyGraph>::adjacency_iterator n_iter, n_end, next;
for (tr1::tie(n_iter, n_end) = boost::adjacent_vertices (*w, G1); n_iter != n_end; ++n_iter)
{
    cout << G1[*n_iter].p_index << endl;
    G1[*n_iter].Graph_Part = Graph_Part::R;
    // boost::clear_vertex(*n_iter, G1); <-- problem
 }
cout << endl << "----" << endl;

如果我取消注释clear_vertex方法,则输出为:

0
3

如果程序删除* n_iter的边缘,则输出仅为:

0
  • 循环在一次迭代后结束 .

1 回答

  • 5

    看看here . remove_vertex 不会改变任何边缘 . 你需要首先 clear_vertex .

    一般提示:不要对 boost::graph 库使用合格的调用,将其称为不合格 . 我也建议Boost.Range在这种简单的情况下处理迭代 . 它使范围更清洁,更漂亮 .

相关问题