【问题标题】:removing vertex and all his neighbours from an graph with c++ boost library使用 c++ boost 库从图中删除顶点和他的所有邻居
【发布时间】:2012-04-24 19:49:38
【问题描述】:

我想从图 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。

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

有人提示我从 Graph 中删除和 Vertex w 与他的所有邻居吗?

更新: 现在我明白了为什么上面的代码不起作用(我正在使用 VertexList=vecS)。我现在尝试将顶点标记为“已移除”并希望移除所有边缘。

图表:

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

- 循环在一次迭代后结束。

【问题讨论】:

    标签: c++ boost graph boost-graph


    【解决方案1】:

    看看hereremove_vertex 不会改变任何边缘。你需要先clear_vertex它。

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

    【讨论】:

    • 嗨,我已经更新了我的问题。如果你能看到更新,我很感激。
    • 在这种情况下使用不合格调用有什么好处?我理解 swap 等,但不是这里。
    • @user1520427 BGL 的扩展方式与std::swap 大致相同。如果您将自己的数据结构调整为Graph,您将在与您的数据结构相同的命名空间中添加额外的函数。
    猜你喜欢
    • 2021-12-30
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多