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> sources;    std::vector<int> targets;    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++;        }

    sources.push_back(node_map[u]);        targets.push_back(node_map[v]);        weights.push_back(w);    }

// 创建igraph图对象    igraph_t graph;    igraph_set_attribute_table(&igraph_cattribute_table);    igraph_empty(&graph, node_count, IGRAPH_UNDIRECTED); 

// 添加边到图中    igraph_vector_int_t source_vector;    igraph_vector_int_init(&source_vector, 0);    for (auto &source : sources) {        igraph_vector_int_push_back(&source_vector, source);    }

igraph_vector_int_t target_vector;    igraph_vector_int_init(&target_vector, 0);    for (auto &target : targets) {        igraph_vector_int_push_back(&target_vector, target);    }

igraph_add_edges(&graph, &source_vector, &target_vector);        // 添加边权重    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);

// 添加节点名称    for (size_t i = 0; i < node_names.size(); ++i) {        SETVAS(&graph, 'name', i, node_names[i].c_str());    }

// 保存图为GraphML格式    FILE *outfile = fopen('gg.graphml', 'w');    igraph_write_graph_graphml(&graph, outfile, false);    fclose(outfile);

// 释放内存    igraph_destroy(&graph);    igraph_vector_int_destroy(&source_vector);    igraph_vector_int_destroy(&target_vector);    igraph_vector_destroy(&weight_vector);

return 0;}

代码解释:

  1. 代码首先包含必要的头文件,并定义了一些变量来存储图数据。2. 然后,代码打开输入文件,读取每一行数据,并将其解析为source节点,target节点和边的权重。3. 接着,代码使用igraph_empty()函数创建一个空的igraph图对象,并使用igraph_add_edges()函数将边添加到图中。4. 代码使用SETEANV()函数将边权重添加到图中。5. 最后,代码使用igraph_write_graph_graphml()函数将图保存为GraphML格式,并使用igraph_destroy()函数释放igraph图对象占用的内存。

总结:

本教程介绍了如何使用C++ igraph库从文件读取数据,构建加权图。您可以根据自己的需要修改代码,例如更改输入文件格式,添加其他属性到图中,或使用其他igraph函数进行图分析。

C++ igraph教程:从文件读取数据构建加权图

原文地址: https://www.cveoy.top/t/topic/fxNE 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录