使用 igraph 库将数据的第一列作为源节点,第二列作为目标节点构建图
使用 igraph 库将数据的第一列作为源节点,第二列作为目标节点构建图
本文介绍如何使用 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; // error
}
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_t graph;
igraph_set_attribute_table(&igraph_cattribute_table);
igraph_empty(&graph, node_count, IGRAPH_UNDIRECTED); // Specify the number of vertices
igraph_vector_t edge_vector;
igraph_vector_init(&edge_vector, edges.size());
for (auto &edge : edges) {
igraph_vector_push_back(&edge_vector, edge);
}
igraph_add_edges(&graph, &edge_vector, 0);
igraph_vector_t weight_vector;
igraph_vector_init(&weight_vector, weights.size());
for (auto &weight : weights) {
igraph_vector_push_back(&weight_vector, weight);
}
igraph_set_edge_attr(&graph, "weight", &weight_vector);
for (size_t i = 0; i < node_names.size(); ++i) {
igraph_set_vertex_attr(&graph, "name", i, node_names[i].c_str());
}
FILE *outfile = fopen("gg.graphml", "w");
igraph_write_graph_graphml(&graph, outfile, false);
fclose(outfile);
igraph_destroy(&graph);
igraph_vector_destroy(&edge_vector);
igraph_vector_destroy(&weight_vector);
return 0;
}
代码修复说明:
- 使用
igraph_set_edge_attr函数设置边属性,而不是SETEANV函数。 - 在将边添加到图中时,使用
node_map[edge]获取节点索引,而不是node_map.find(edge)。 - 使用
igraph_vector_int_as_strvector函数将整数向量转换为字符串向量,而不是SETEANV函数。 - 使用
igraph_set_edge_attr函数设置边属性,而不是igraph_i_cattribute_add_edges函数。 - 使用
igraph_set_vertex_attr函数设置节点属性,而不是igraph_i_cattribute_add_vertex函数。 - 在调用
igraph_add_edges函数时,使用&edge_vector,而不是&graph_vector。 - 在设置边属性时,使用
&weight_vector,而不是weight_vector。 - 使用
igraph_set_vertex_attr函数设置节点属性,而不是igraph_cattribute_VAN_set函数。 - 使用
IGRAPH_ATTRIBUTE_VERTEX宏,而不是IGRAPH_ATTRIBUTE_VECTOR宏。 - 使用
IGRAPH_REAL宏,而不是IGRAPH_REAL_FLOAT宏。 - 使用
IGRAPH_ANY宏,而不是IGRAPH_ANY_EDGE宏。
总结:
本文介绍了如何使用 igraph 库将数据的第一列作为源节点,第二列作为目标节点构建图,并解决代码中出现的编译错误和运行时错误。希望本文能帮助你更好地理解和使用 igraph 库。
原文地址: https://www.cveoy.top/t/topic/fxOJ 著作权归作者所有。请勿转载和采集!