图论系列之「读取图算法」
图的读取算法
一、图的读取
在这小节中我们将会学习到啊这样将文件读如图中,前面我们学了稠密图和稀疏图,为了统一接口我们使用模板类,让其同时具备读入两种图的能力。
代码实现
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cassert>
using namespace std;
// 读取图算法
//使用模板Graph,统一接口
template <typename Graph>
class ReadGraph{
public:
// 从文件filename中读取图的信息, 存储进图graph中
ReadGraph(Graph &graph, const string &filename){
ifstream file(filename);
string line;
int V, E;
assert( file.is_open() );
// 第一行读取图中的节点个数和边的个数
//将file中的第一行读入line中
assert( getline(file, line) );
stringstream ss(line);
ss>>V>>E;
assert( V == graph.V() );
// 读取每一条边的信息
for( int i = 0 ; i < E ; i ++ ){
assert( getline(file, line) );
stringstream ss(line);
int a,b;
ss>>a>>b;
assert( a >= 0 && a < V );
assert( b >= 0 && b < V );
//调用图中函数添加边
graph.addEdge( a , b );
}
}
};
本作品采用《CC 协议》,转载必须注明作者和本文链接