take
take

Reputation: 2222

removing vertex and all his neighbours from an graph with c++ boost library

I want to remove a vertex w with his neighbours from an graph G.

My Code:

// 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;
    }
}

I tried to iterate through the adjacent vertexes and delete them. After that i tried to remove the vertex w.

But there come some Exceptions and Errors while starting the program.

Have somebody an hint for me to remove and Vertex w with all of his neighbours from an Graph?

Update: Now I understand why the code above won't work (I'm Using VertexList=vecS). I now try to mark the Vertex as "removed" and want to remove all edges.

Graph:

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

Code:

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;

If i uncomment the clear_vertex method, the output is:

0
3

If the program remove the edges of *n_iter, the output is only:

0

- the loop ends after one iteration.

Upvotes: 2

Views: 3417

Answers (1)

pmr
pmr

Reputation: 59811

Have a look here. remove_vertex will not change any edges. You need to clear_vertex it first.

A general hint: Don't use qualified calls to the boost::graph library, call them unqualified. I'd also suggest Boost.Range to handle the iteration in such simple cases. It keeps the scope cleaner and is a lot prettier.

Upvotes: 5

Related Questions