【图论实战】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)
相关推荐
l1t14 分钟前
DeepSeek总结的DuckDB 2.0.0 中的隐藏亮点
大数据·数据库·duckdb
程序员塔塔喵26 分钟前
【MySQL篇|第八篇】索引底层实现
数据库·mysql·adb·索引
kyrie_sakura29 分钟前
大模型学习17 大模型学习 - LangChain1_概述
学习
updayday8541 小时前
电脑换了硬盘、加了内存,资产台账却没更新 - Ping64 硬件资产管理
大数据·网络·数据库·安全·智能路由器
hhhjhl1 小时前
mime-types 跨端三方库仓颉适配全流程
数据库
程序猿乐锅1 小时前
【从0-1学习Python | 第九篇】继承
开发语言·后端·python·学习·fastapi
广州智造1 小时前
Radioss中破坏模型FAILTAB1的详细介绍
数据库·人工智能·算法·机器学习·仿真软件·radioss
李兆龙的博客1 小时前
从一到无穷大 #101:SSD 的工作原理——从 NAND 到数据库读写
数据库·ssd·存储
吹什么轩1 小时前
MySQL 内置函数全景:日期 / 字符串 / 数学 / 其他,一次讲透(附索引杀手排查)
java·数据库·面试
CS创新实验室1 小时前
改了模型,数据库为什么能自动跟上?——Django 迁移(migrations)的底层
数据库·django·sqlite