C++ c++;从图中删除顶点

C++ c++;从图中删除顶点,c++,boost,graph,C++,Boost,Graph,3使用boost.1.46.1进行以下编译 #include <boost/graph/adjacency_list.hpp> struct Node { int id; }; struct Edge { int source; int target; int weight; }; int main() { /* an adjacency_list like we need it */ typedef boost::adjacency_list<

3使用boost.1.46.1进行以下编译

#include <boost/graph/adjacency_list.hpp>

struct Node {
  int id;
};

struct Edge {
  int source;
  int target;
  int weight;
};

int main() {
  /* an adjacency_list like we need it */
  typedef boost::adjacency_list<
    boost::setS, // edge container
    boost::listS, // vertex container
    boost::bidirectionalS, // directed graph
    Node, Edge> Graph;

  typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;

  Graph gp1;

  std::cout << "Number of vertices 1: " << boost::num_vertices(gp1) << std::endl;
  Vertex v1 = boost::add_vertex(gp1);
  Vertex v2 = boost::add_vertex(gp1);

  std::cout << "Number of vertices 2: " << boost::num_vertices(gp1) << std::endl;

  gp1[v1].id = 3;
  gp1[v2].id = 4;

  Graph gp2(gp1);

  std::cout << "Number of vertices 3: " << boost::num_vertices(gp2) << std::endl;

  boost::remove_vertex(v2, gp2);

  std::cout << "Number of vertices 4: " << boost::num_vertices(gp1) << std::endl;
  std::cout << "Number of vertices 5: " << boost::num_vertices(gp2) << std::endl;

  boost::graph_traits<Graph>::vertex_iterator it, end;
  for (boost::tie( it, end ) = vertices(gp2); it != end; ++it) {
    if ( gp2[*it].id == 3 ) {
      boost::remove_vertex(*it, gp2);
    }
  }

  std::cout << "Number of vertices 6: " << boost::num_vertices(gp1) << std::endl;
  std::cout << "Number of vertices 7: " << boost::num_vertices(gp2) << std::endl;

  return 0;
}
#包括
结构节点{
int-id;
};
结构边{
int源;
int目标;
整数权重;
};
int main(){
/*我们需要的邻接列表*/
typedef boost::邻接列表<
boost::set,//边缘容器
boost::list,//顶点容器
boost::双向,//有向图
节点,边>图;
typedef boost::graph_traits::vertex_描述符顶点;
图gp1;

std::cout在迭代顶点集合时修改它

首先收集要删除的顶点,然后删除它们。或使用以下模式:

// Remove all the vertices. This is OK.
graph_traits<Graph>::vertex_iterator vi, vi_end, next;
tie(vi, vi_end) = vertices(G);
for (next = vi; vi != vi_end; vi = next) {
  ++next;
  remove_vertex(*vi, G);
}
输出:

Number of vertices 1: 0
Number of vertices 2: 2
Number of vertices 3: 2
Number of vertices 4: 1
Number of vertices 5: 2
Number of vertices 6: 1
Number of vertices 7: 1

不再发生崩溃:)

请注意,sehe的解决方案仅适用于VertexList=List的图,特别是不适用于VertexList=vecS的图。还请注意,通常不能存储顶点描述符或迭代器并在以后删除它们,因为:

无效删除顶点(顶点描述符、邻接列表和g)

…如果 邻接列表的VertexList模板参数为vecS,然后为all 图的顶点描述符、边描述符和迭代器是 此操作使其无效。的内置顶点索引属性 每个顶点都将重新编号,以便在操作后顶点 索引仍然形成一个连续的范围[0,num_顶点(g))


好的,阅读文档我理解remove_vertex()失效/稳定性,但我的第一个问题是什么。当我将gp1复制到gp2时,“boost::remove_vertex(v2,gp2)”如何工作?为什么它会将gp1减少1个顶点?
Number of vertices 1: 0
Number of vertices 2: 2
Number of vertices 3: 2
Number of vertices 4: 1
Number of vertices 5: 2
Number of vertices 6: 1
Number of vertices 7: 1