第四周作业——图的表示
2014-04-03 00:33
363 查看
由于二重指针不能直接指向二维数组,因此此处输出到txt文档的函数不使用指针参数,但出现了乱码,有待研究中 #include <iostream> #include "stdafx.h" #include <fstream> #include <string.h> using namespace std; #define NUM_AMOUNT 26 //有连接边的顶点数为26 #define VERTEX_NUM 13 //图的顶点数为13 #define EGDE_NUM 13 //边的数目为13 void getDataFromFile(const char *filename,int *data) //将txt文档的数字存入data数组 { ifstream fin; int index = 0; fin.open(filename, ios::in); if (!fin) { cerr << "the fucking file openning failed!" << endl; exit(1); } //忽略读入顶点数和边数 fin.ignore(5,'/n'); while(!fin.eof()) { fin >> data[index++]; } fin.close(); //return index; } void writeToFile(const char * fileneme, int tem_array[VERTEX_NUM][VERTEX_NUM], int index) //将排序好的数组数据写入新的txt文档 { fstream datafile; datafile.open(fileneme, ios::out|ios::trunc); if (!datafile) { cerr << "file open failed!" << endl; exit(1); } for (int i = 0; i < index; i ++) { for (int j = 0; j < index; j ++) { datafile << tem_array[i][j]; } } datafile.close(); } //template <class DataType> class GraphRepresentation { public: GraphRepresentation(int array[], int v, int e); ~GraphRepresentation(){}; void pullMatrix(int array[]); //对邻接矩阵数组填充0和1 void printMatrix(); //打印邻接矩阵数组 void getMatrix(int tem_array[VERTEX_NUM][VERTEX_NUM]); private: int vertexNum, egdeNum; int adj_matrix[VERTEX_NUM][VERTEX_NUM]; //int vertex[VERTEX_NUM]; //int egde[EGDE_NUM][EGDE_NUM]; }; GraphRepresentation::GraphRepresentation(int array[], int v, int e) { vertexNum = v; egdeNum = e; for (int i = 0; i < VERTEX_NUM; i ++) //初始化邻接矩阵数组 { for (int j = 0; j < VERTEX_NUM; j ++) { adj_matrix[i][j] = 0; } } } void GraphRepresentation::pullMatrix(int array[]) { int a = 0,b = 0; for (int i = 0; i < NUM_AMOUNT - 1; i = i +2) { a = array[i]; b = array[i + 1]; adj_matrix[a][b] = adj_matrix[b][a] = 1; } } void GraphRepresentation::printMatrix() { for (int i = 0; i < VERTEX_NUM; i ++) { for (int j = 0; j < VERTEX_NUM; j ++) { cout << adj_matrix[i][j] << " "; } cout << endl; } } void GraphRepresentation::getMatrix(int tem_array[VERTEX_NUM][VERTEX_NUM]) { for (int i = 0; i < VERTEX_NUM; i ++) { for (int j = 0; j < VERTEX_NUM; j ++) { tem_array[i][j] = adj_matrix[i][j]; } } } int main() { int * data = new int[NUM_AMOUNT]; int adj_tem_matrix[VERTEX_NUM][VERTEX_NUM]; int matrix_num = VERTEX_NUM * VERTEX_NUM; getDataFromFile("tinyG.txt", data); GraphRepresentation mGraph(data, VERTEX_NUM, EGDE_NUM); mGraph.pullMatrix(data); mGraph.printMatrix(); mGraph.getMatrix(adj_tem_matrix); writeToFile("tinyG_matrix.txt", adj_tem_matrix, matrix_num); delete []data; return 0; }