建立一个ReadGraph.h文件读入txt中存储的图
#include <iostream>
#include <ctime>
#include <cstdlib>
#include "SparseGraph.h"
#include "DenseGraph.h"
#include "ReadGraph.h"
using namespace std;
int main()
{
string filename = "testG1.txt";
SparseGraph g1( 13, false );
ReadGraph<SparseGraph> readGraph1( g1, filename );
g1.show();
cout<<endl;
DenseGraph g2( 13, false );
ReadGraph<DenseGraph> readGraph2( g2, filename );
g2.show();
return 0;
}
"testG1.txt"中为
第一行第一个13代表13个顶点,第二个13代表13条边,
下面的每一行表示两个顶点相连
13 13
0 5
4 3
0 1
9 12
6 4
5 4
0 2
11 12
9 10
0 6
7 8
9 11
5 3
"ReadGraph.h"定义为
#include <iostream>
#include <string>
#include <fstream>
#include <sstream>
#include <cassert>
using namespace std;
template<typename Graph>
class ReadGraph{
public:
ReadGraph(Graph &graph, const string &filename){
ifstream file(filename.c_str());
string line;
int V,E;
assert( file.is_open() );
assert( getline(file, line) );
stringstream ss(line);
ss>>V>>E;
assert( V == graph.V() )