boost快速入门

boost库简单使用

建图

typedef adjacency_list<vecS, vecS, bidirectionalS> Graph;
头两个模板参数(vecS, vecS)分别用来描述离开顶点的out-edges边图中顶点的集合
bidirectionalS表示选择一个可访问出、入边的有向图,directedS 为选择一个仅提供出边的有向图;undirectedS 表示选择一个无向图

1.用pairs 数组 edge_array来建立边

typedef std::pair<int, int> Edge;
Edge edge_array[] = {
    Edge(A,B), Edge(A,D), Edge(C,A), Edge(D,C),Edge(C,E), Edge(B,D), Edge(D,E) }
const int num_edges = sizeof(edge_array)/sizeof(edge_array[0]);
 Graph g(num_vertices);
    // 给图对象添加边
 for (int i = 0; i < num_edges; ++i)
 add_edge(edge_array[i].first, edge_array[i].second, g);//其中first表示第一个顶点,second表示第二个顶点,两个顶点连接

或者
2.

Graph g(edge_array, edge_array + sizeof(edge_array) / sizeof(Edge), num_vertices);

其中edge_array是边集合。同样可以使用 MutableGraph 接口的add_vertex()和remove_vertex() 来为图添加和删除顶点

访问顶点集合:

通过VertexListGraph 接口的vertices() 函数
这个函数返回一个顶点迭代器的std::pair 类型(第一个迭代器指向顶点的开始,第二个迭代器指向顶点的结束)
给定一个图类型,graph_traits类能提供该图的vertex_iterator类型
property_map 类可用来获得指定属性(通过指定BGL预定义的vertex_index_t来取得索引)的property_map 类型,通过调用函数get(vertex_index, g) 来获得图当前的property_map对象。

typedef property_map<Graph, vertex_index_t>::type IndexMap;
IndexMap index = get(vertex_index, g);

typedef graph_traits<Graph>::vertex_iterator vertex_iter;
    std::pair<vertex_iter, vertex_iter> vp;
    for (vp = vertices(g); vp.first != vp.second; ++vp.first)
            std::cout << index[*vp.first] << " ";

vertices(g) = 0 1 2 3 4

访问边集合

边集合可以使用EdgeListGraph接口中的 edges()函数访问
返回一对边迭代器edge iterators
调用**source()target()函数可以取得边连接的两个顶点
使用
tie()**辅助函数,而不是为迭代器声明一个pair类型,这个便利的函数可以用来分开std::pair 到两个分离的变量,这里是ei 和 ei_end,这样比创建一个std::pair 类型方便

typedef property_map<Graph, vertex_index_t>::type IndexMap;
    IndexMap index = get(vertex_index, g);
 
    std::cout << "edges(g) = ";
    graph_traits<Graph>::edge_iterator ei, ei_end;
    for (tie(ei, ei_end) = edges(g); ei != ei_end; ++ei)
       std::cout << "(" << index[source(*ei, g)]<< "," << index[target(*ei, g)] << ") "

edges(g) = (0,1) (0,2) (0,3) (0,4) (2,0) (2,4) (3,0)(3,1) (3,4) (4,0) (4,1)

一些使用boost库的示范程序:

//在 Boost 头文件 adjacency_list.hpp 中如何声明邻接表
template <class OutEdgeListS = vecS, 
// a Sequence or an AssociativeContainer class VertexListS = vecS, 
// a Sequence or a RandomAccessContainer class DirectedS = directedS, 
class VertexProperty = no_property, 
class EdgeProperty = no_property, //权重其实就在这里
class GraphProperty = no_property, 
class EdgeListS = listS> 
class
  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值