boost Graph 动态加点加边
时间: 2023-08-26 17:36:24 浏览: 47
要在 Boost Graph 中进行动态加点和加边,可以使用 Boost Graph Library 提供的 insert_vertex 和 add_edge 函数。
insert_vertex 函数用于向图中插入一个新的顶点,其函数原型为:
```cpp
vertex_descriptor insert_vertex(Graph& g);
```
其中,Graph 是图的类型,vertex_descriptor 是一个整数类型,表示顶点描述符,可以用来引用该顶点。
例如,我们可以创建一个无向图,并向其中插入一个顶点,代码如下:
```cpp
#include <boost/graph/adjacency_list.hpp>
using namespace boost;
typedef adjacency_list<vecS, vecS, undirectedS> Graph;
int main() {
Graph g;
// 插入一个顶点
Graph::vertex_descriptor v = add_vertex(g);
return 0;
}
```
add_edge 函数用于向图中添加一条新的边,其函数原型为:
```cpp
edge_descriptor add_edge(vertex_descriptor u, vertex_descriptor v, Graph& g);
```
其中,u 和 v 是边的两个端点,g 是图的类型,edge_descriptor 是一个整数类型,表示边的描述符,可以用来引用该边。
例如,我们可以创建一个无向图,并向其中添加两个顶点和一条边,代码如下:
```cpp
#include <boost/graph/adjacency_list.hpp>
using namespace boost;
typedef adjacency_list<vecS, vecS, undirectedS> Graph;
int main() {
Graph g;
// 插入两个顶点
Graph::vertex_descriptor v1 = add_vertex(g);
Graph::vertex_descriptor v2 = add_vertex(g);
// 添加一条边
add_edge(v1, v2, g);
return 0;
}
```
需要注意的是,在使用 add_edge 函数之前,必须已经添加了边的两个端点。如果在调用 add_edge 函数时,其中一个端点不存在,程序将会崩溃。因此,在添加边之前,应该先添加顶点。