【图论实战】Boost学习 01:基本操作

文章目录

头文件

cpp 复制代码
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graphviz.hpp>
#include <boost/graph/properties.hpp>
#include <boost/property_map/property_map.hpp>
#include <boost/graph/named_function_params.hpp>
//#include<boost/graph/dijkstra_shortest_paths.hpp>
#include <iostream>
#include <fstream>
using namespace boost;
using namespace std;

图的构建

参考网址

cpp 复制代码
// 无属性图的定义
typedef adjacency_list<vecS, //表示顶点是用vector来存储的
					   vecS, // 表示边是用vector来存储的
					   directedS, //表示有向图
					   no_property, //表示不带属性
					   no_property> //表示不带属性
					   MyGraphType;


// 有属性图的定义
struct VertexProperty{
	int id;
	string name;
};
struct EdgeProperty{
	int id;
	int weight;
};
typedef boost::adjacency_list<vecS, 			//使用数组来存储vertex vecS,
							  bidirectionalS, 	//声明为有向图,可以访问其out-edge,若要都能访问
							  VertexProperty, 	//定义顶点属性
							  EdgeProperty> 	//定义边的属性 > Graph;在此之前,要定义顶点和边的属性,可以用结构体自定义
							  MyGraphType;
					   
// 创建图	
MyGraphType G;
auto v0=add_vertex(G);
auto v1=add_vertex(G);
auto v2=add_vertex(G);
auto v3=add_vertex(G);
auto e01=add_edge(v0,v1,G);
auto e12=add_edge(v1,v2,G);
auto e23=add_edge(v2,v3,G);
auto e30=add_edge(v3,v0,G);
// 设置权重
property_map<MyGraphType,edge_weight_t>::type weightmap= get(boost::edge_weight, G);
weightmap[e]=10.1; 		// 方式1
put(weightmap,e,20); 	// 方式2
// 获取顶点ID

图的可视化

方式一: 利用graphviz

1、将图保存为gv文件

cpp 复制代码
// g is the graph
boost::dynamic_properties dp;
dp.property("node_id", get(boost::vertex_index, G));
dp.property("label",  get(boost::edge_weight,  G));
ofstream outf("min.gv");
write_graphviz_dp(outf, G,dp);

2、将gv文件转化为png文件
工具下载 graphviz 2.38


在线转换工具

方式二: 打印结果

cpp 复制代码
auto vpair =vertices(G);
for(auto iter=vpair.first;iter!=vpair.second;iter++){
	cout<<"vertex "<<*iter<<endl;
}

auto epair=edges(G);
for(auto iter=epair.first;iter!=epair.second;iter++){
	cout<<"edge "<<source(*iter,G)<<" - "<<target(*iter,G)<<endl;
}	

基本操作

cpp 复制代码
// 获取顶点个数
boost::num_vertices(g)
相关推荐
Nan_Shu_61436 分钟前
学习: 尚硅谷Java项目之小谷充电宝(3)
java·后端·学习
沙漏无语36 分钟前
(二)TIDB搭建正式集群
linux·数据库·tidb
头疼的程序员38 分钟前
计算机网络:自顶向下方法(第七版)第三章 学习分享(二)
网络·学习·计算机网络
星期五不见面42 分钟前
AI学习(三)openclow启动(2)2026/03/05
学习
姚不倒42 分钟前
三节点 TiDB 集群部署与负载均衡搭建实战
运维·数据库·分布式·负载均衡·tidb
隔壁小邓1 小时前
批量更新方式与对比
数据库
数据知道1 小时前
MongoDB复制集架构原理:Primary、Secondary 与 Arbiter 的角色分工
数据库·mongodb·架构
人道领域1 小时前
苍穹外卖:菜品新增功能全流程解析
数据库·后端·状态模式
修行者Java1 小时前
(七)从 “非结构化数据难存储” 到 “MongoDB 灵活赋能”——MongoDB 实战进阶指南
数据库·mongodb