使用c++读取邻接矩阵然后使用boost库的graph计算每个节点的度和所属的模块最后将结果输出
以下是使用C++读取邻接矩阵并使用Boost库的graph计算每个节点的度和所属的模块,并将结果输出的示例代码:
#include <iostream>
#include <fstream>
#include <vector>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/graph_traits.hpp>
#include <boost/graph/connected_components.hpp>
// 定义图类型
typedef boost::adjacency_list<boost::vecS, boost::vecS, boost::undirectedS> Graph;
// 定义节点类型
typedef boost::graph_traits<Graph>::vertex_descriptor Vertex;
int main() {
std::ifstream file("adjacency_matrix.txt"); // 读取邻接矩阵文件
if (!file) {
std::cerr << "Error opening file." << std::endl;
return 1;
}
int numVertices;
file >> numVertices; // 读取节点数量
// 创建图对象
Graph g(numVertices);
// 读取邻接矩阵数据并添加边
for (int i = 0; i < numVertices; ++i) {
for (int j = 0; j < numVertices; ++j) {
int value;
file >> value;
if (value != 0) {
boost::add_edge(i, j, g);
}
}
}
file.close();
// 计算节点度
std::vector<int> degrees(numVertices);
boost::graph_traits<Graph>::vertex_iterator vertexIt, vertexEnd;
for (boost::tie(vertexIt, vertexEnd) = boost::vertices(g); vertexIt != vertexEnd; ++vertexIt) {
degrees[*vertexIt] = boost::out_degree(*vertexIt, g);
}
// 计算节点所属的模块
std::vector<int> component(numVertices);
int numComponents = boost::connected_components(g, &component[0]);
// 输出结果
std::cout << "Node degrees:" << std::endl;
for (int i = 0; i < numVertices; ++i) {
std::cout << "Node " << i << ": " << degrees[i] << std::endl;
}
std::cout << "Node components:" << std::endl;
for (int i = 0; i < numVertices; ++i) {
std::cout << "Node " << i << ": " << component[i] << std::endl;
}
return 0;
}
假设邻接矩阵数据保存在名为"adjacency_matrix.txt"的文件中,文件格式如下:
5 // 节点数量
0 1 1 0 0
1 0 0 1 0
1 0 0 1 0
0 1 1 0 1
0 0 0 1 0
代码中使用了boost::adjacency_list来表示图,其中boost::vecS用于指定节点容器类型为vector,boost::undirectedS表示图是无向的。boost::add_edge用于添加边,boost::out_degree用于计算节点的度,boost::connected_components用于计算节点的模块。最后,使用std::cout输出结果。
请根据实际情况修改代码中的文件名和文件格式,并根据需要进行适当的调整
原文地址: https://www.cveoy.top/t/topic/ilVO 著作权归作者所有。请勿转载和采集!