【图论实战】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)
相关推荐
Nturmoils1 天前
订单列表慢查询,先看 WHERE、ORDER BY 和 LIMIT
数据库
渣波1 天前
拒绝 SQL 焦虑!手把手带你用 NestJS + Prisma + DTO 写出“防弹”级后端代码
javascript·数据库·后端
倔强的石头_2 天前
KingbaseES 新版MySQL 兼容版体验:旧版迁移 + 功能实测
数据库
倔强的石头_5 天前
《Kingbase护城河》——数据库存储空间全景探测与精细化瘦身实战
数据库
冬奇Lab6 天前
每日一个开源项目(第134篇):Zvec - 阿里开源的嵌入式向量数据库,向量搜索界的 SQLite
数据库·人工智能·llm
ClouGence6 天前
Oracle CDC 架构优化:从主库直连到 DataGuard 备库同步
数据库·后端·oracle
无响应de神6 天前
三、用户与权限管理
数据库·mysql
通信小呆呆7 天前
当算法有了“五感”:多模态数据融合如何向人体感官协同学习?
人工智能·学习·算法·机器学习·机器人
H__Rick7 天前
自动对焦学习-3
人工智能·学习·计算机视觉
Daisy Lee7 天前
量化学习-第1章-什么是量化金融
学习·金融·datawhale