From ee2503b5a7aa96d35b1ca03006215ad93f6f21ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BE=A1=E5=9D=82=E6=98=B4?= Date: Fri, 6 Dec 2024 01:34:39 +0800 Subject: [PATCH] =?UTF-8?q?to=5Fstring=E5=86=99=E5=A5=BD=EF=BC=8C=E5=8F=91?= =?UTF-8?q?=E7=8E=B0connect=E5=87=BD=E6=95=B0=E7=9A=84bug?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- homework5/MatrixGraph.h | 35 +++++++++++++++++++++++++++++++++-- homework5/test1.cpp | 16 +++++++++++++++- 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/homework5/MatrixGraph.h b/homework5/MatrixGraph.h index 7804259..2840b0c 100644 --- a/homework5/MatrixGraph.h +++ b/homework5/MatrixGraph.h @@ -5,6 +5,7 @@ #ifndef MATRIXGRAPH_H #define MATRIXGRAPH_H +#include #include #include "GraphExceptions/InsertExistedConnectException.h" @@ -18,6 +19,10 @@ private: struct connection { T weight; //权 bool connected; //是否连接 + connection() { + weight = 0; + connected = false; + } }; vector data; //顶点值 @@ -35,9 +40,9 @@ public: // 添加顶点 void insert(T value) { data.push_back(value); - matrix.push_back(vector(0, false)); //添加一行 + matrix.push_back(vector()); //添加一行 for (auto &row: matrix) { - row.resize(data.size(), connection(0, false)); // 扩展列 + row.resize(data.size(), connection()); // 扩展列 } } @@ -66,5 +71,31 @@ public: matrix[id2][id1].weight = weight; } } + + // 打印matrix + string to_string() { + stringstream ss; + for (int i = 0; i < matrix.size(); ++i) { + for (int j = 0; j < matrix[i].size(); ++j) { + if (j == matrix[i].size() - 1) { + //判断是否哦是最后一个元素 + if (isWeighted) { + // 判断是否加权 + ss << matrix[i][j].connected << "|" << matrix[i][j].weight; + } else { + ss << matrix[i][j].connected; + } + } else { + if (isWeighted) { + ss << matrix[i][j].connected << "|" << matrix[i][j].weight << " "; + } else { + ss << matrix[i][j].connected << " "; + } + } + } + ss << endl; + } + return ss.str(); + } }; #endif //MATRIXGRAPH_H diff --git a/homework5/test1.cpp b/homework5/test1.cpp index 72d9bca..e8f9361 100644 --- a/homework5/test1.cpp +++ b/homework5/test1.cpp @@ -24,6 +24,20 @@ #include #include"MatrixGraph.h" using namespace std; + int main() { + MatrixGraph graph = new MatrixGraph(); + int n, e; + cin >> n >> e; + for (int i = 0; i < n; i++) { + graph.insert(i); + } + for (int i = 0; i < e; i++) { + int id1, id2; + cin >> id1 >> id2; + graph.connect(id1, id2); + } + cout << "图的邻接矩阵为:" << endl; + cout << graph.to_string() << endl; return 0; -} \ No newline at end of file +}