C++ 使用 Boost 库绘制网络图并导出为 PDF 文件
#include
int main() { // 读取矩阵数据 int matrix[5][5] = { {0, 1, 1, 0, 0}, {1, 0, 0, 1, 1}, {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 1, 0, 0, 0} };
// 创建图对象
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;
Graph g;
// 添加顶点
for (int i = 0; i < 5; ++i) {
boost::add_vertex(g);
}
// 添加边
for (int i = 0; i < 5; ++i) {
for (int j = i + 1; j < 5; ++j) {
if (matrix[i][j] == 1) {
boost::add_edge(i, j, g);
}
}
}
// 导出为pdf
std::ofstream output("graph.pdf");
boost::write_graphviz(output, g);
std::cout << "Graph exported to graph.pdf" << std::endl;
return 0;
}
该代码首先定义了一个5x5的矩阵,表示顶点之间的连接关系。然后使用boost库的adjacency_list创建了一个无向图对象。接着通过遍历矩阵,将矩阵中对应的位置为1的边添加到图中。最后使用write_graphviz函数将图导出为graph.pdf文件。
请确保在编译代码时已经安装了boost库,并在编译命令中链接boost库。
原文地址: https://www.cveoy.top/t/topic/p2Nc 著作权归作者所有。请勿转载和采集!