C++ igraph教程:从数据文件构建图并设置边权重和节点名称
#include <igraph/igraph.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <unordered_map>
#include <vector>
int main() {
// 打开数据文件
std::ifstream file('matrix.txt');
std::string line;
// 初始化数据结构
std::vector<int> edges;
std::vector<double> weights;
std::vector<std::string> node_names;
std::unordered_map<std::string, int> node_map;
int node_count = 0;
// 读取数据文件并构建图
while (std::getline(file, line)) {
std::istringstream iss(line);
std::string u, v;
double w;
// 解析每一行数据
if (!(iss >> u >> v >> w)) {
break; // 如果解析出错,跳出循环
}
// 处理源节点
if (node_map.find(u) == node_map.end()) {
// 如果节点不存在,将其添加到映射表和节点名称列表中
node_map[u] = node_count;
node_names.push_back(u);
node_count++;
}
// 处理目标节点
if (node_map.find(v) == node_map.end()) {
// 如果节点不存在,将其添加到映射表和节点名称列表中
node_map[v] = node_count;
node_names.push_back(v);
node_count++;
}
// 添加边和权重
edges.push_back(node_map[u]);
edges.push_back(node_map[v]);
weights.push_back(w);
}
// 创建 igraph 图对象
igraph_t graph;
igraph_empty(&graph, node_count, IGRAPH_UNDIRECTED);
// 添加边到图中
igraph_vector_int_t edge_vector;
igraph_vector_int_init(&edge_vector, edges.size());
for (auto &edge : edges) {
igraph_vector_int_push_back(&edge_vector, edge);
}
igraph_add_edges(&graph, &edge_vector, 0);
igraph_vector_int_destroy(&edge_vector);
// 设置边权重
igraph_vector_t weights_vector;
igraph_vector_init(&weights_vector, weights.size());
for (auto &weight : weights) {
igraph_vector_push_back(&weights_vector, weight);
}
igraph_cattribute_VAN_set(&graph, 'weight', 0, &weights_vector);
igraph_vector_destroy(&weights_vector);
// 设置节点名称
igraph_strvector_t names_vector;
igraph_strvector_init(&names_vector, node_names.size());
for (auto &name : node_names) {
igraph_strvector_add(&names_vector, name.c_str());
}
igraph_cattribute_VAS_setv(&graph, 'name', &names_vector);
igraph_strvector_destroy(&names_vector);
// 将图保存为GraphML文件
FILE *outfile = fopen('gg.graphml', 'w');
igraph_write_graph_graphml(&graph, outfile, IGRAPH_ALL);
fclose(outfile);
// 销毁图对象
igraph_destroy(&graph);
return 0;
}
原文地址: https://www.cveoy.top/t/topic/fxON 著作权归作者所有。请勿转载和采集!