C++ igraph教程:从数据文件构建图并设置边属性
C++ igraph教程:从数据文件构建图并设置边属性
本教程将演示如何使用C++ igraph库从数据文件构建图,并将数据文件的第一列和第二列分别设置为边的'source'和'target'属性。
代码示例cpp#include <igraph/igraph.h>#include #include #include #include <unordered_map>#include
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_int_t edge_vector; igraph_vector_int_init(&edge_vector, 0);
for (auto &edge : edges) { igraph_vector_int_push_back(&edge_vector, edge); }
igraph_add_edges(&graph, &edge_vector, 0);
igraph_vector_t weight_vector; igraph_vector_init(&weight_vector, 0);
for (auto &weight : weights) { igraph_vector_push_back(&weight_vector, weight); }
SETEANV(&graph, 'weight', &weight_vector);
// Add source and target attributes igraph_vector_t source_vector, target_vector; igraph_vector_init(&source_vector, 0); igraph_vector_init(&target_vector, 0);
for (size_t i = 0; i < edges.size(); i += 2) { igraph_vector_push_back(&source_vector, edges[i]); igraph_vector_push_back(&target_vector, edges[i + 1]); }
SETVASV(&graph, 'source', &source_vector); SETVASV(&graph, 'target', &target_vector);
for (size_t i = 0; i < node_names.size(); ++i) { SETVAS(&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_int_destroy(&edge_vector); igraph_vector_destroy(&weight_vector); igraph_vector_destroy(&source_vector); igraph_vector_destroy(&target_vector);
return 0;}
代码说明
- 读取数据文件: 代码首先读取名为 'matrix.txt' 的数据文件。假设该文件每行包含三个值:边的起点节点,终点节点和边的权重。2. 构建节点映射: 代码使用
unordered_map存储节点名和对应id的映射关系。3. 创建igraph图: 使用igraph_empty函数创建一个空的无向图,节点数为node_count。4. 添加边: 使用igraph_add_edges函数将边添加到图中。5. 设置边权重: 使用SETEANV函数将边权重属性添加到图中。6. 设置'source'和'target'属性: 代码遍历边列表,并将每条边的起点和终点分别存储到source_vector和target_vector中。最后,使用SETVASV函数将这两个向量设置为图的 'source' 和 'target' 属性。7. 保存图: 使用igraph_write_graph_graphml函数将图保存到名为 'gg.graphml' 的 GraphML 文件中。
总结
本教程介绍了如何使用 C++ igraph 库从数据文件构建图,并设置边的 'source' 和 'target' 属性。这些属性对于分析和可视化图数据非常有用。
原文地址: https://www.cveoy.top/t/topic/fxNG 著作权归作者所有。请勿转载和采集!