【图论实战】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)
相关推荐
2301_7965125214 分钟前
Rust编程学习 - 为什么说Cow 代表的是Copy-On-Write, 即“写时复制技术”,它是一种高效的 资源管理手段
java·学习·rust
故里213015 分钟前
学习前端记录(二)21-40
学习
编啊编程啊程17 分钟前
【029】智能停车计费系统
java·数据库·spring boot·spring·spring cloud·kafka
ThreeYear_s43 分钟前
电力电子技术学习路径与FPGA/DSP技术结合方向(gemini生成)
学习·fpga开发
Leon-Ning Liu1 小时前
Oracle数据库常用视图:dba_datapump_jobs
数据库·oracle·dba
好奇龙猫1 小时前
【生活相关-日语-日本-入国&出国-海关&市役所(4)-办理手续】
学习·生活
sendnews1 小时前
红松小课如何成为激活老年人生活的新引擎?从兴趣学习到价值重塑!
学习·生活
数据库生产实战1 小时前
Oracle 19C RAC下TRUNCATE TABLE的REUSE STORAGE选项作用和风险浅析!
数据库·oracle
The_Second_Coming2 小时前
ELK 学习笔记
笔记·学习·elk
wdfk_prog2 小时前
[Linux]学习笔记系列 -- [kernel][time]timekeeping
linux·笔记·学习