to_string写好,发现connect函数的bug

This commit is contained in:
2024-12-06 01:34:39 +08:00
parent 80e8826057
commit ee2503b5a7
2 changed files with 48 additions and 3 deletions
+33 -2
View File
@@ -5,6 +5,7 @@
#ifndef MATRIXGRAPH_H #ifndef MATRIXGRAPH_H
#define MATRIXGRAPH_H #define MATRIXGRAPH_H
#include <sstream>
#include<vector> #include<vector>
#include "GraphExceptions/InsertExistedConnectException.h" #include "GraphExceptions/InsertExistedConnectException.h"
@@ -18,6 +19,10 @@ private:
struct connection { struct connection {
T weight; //权 T weight; //权
bool connected; //是否连接 bool connected; //是否连接
connection() {
weight = 0;
connected = false;
}
}; };
vector<T> data; //顶点值 vector<T> data; //顶点值
@@ -35,9 +40,9 @@ public:
// 添加顶点 // 添加顶点
void insert(T value) { void insert(T value) {
data.push_back(value); data.push_back(value);
matrix.push_back(vector<connection>(0, false)); //添加一行 matrix.push_back(vector<connection>()); //添加一行
for (auto &row: matrix) { 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[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 #endif //MATRIXGRAPH_H
+14
View File
@@ -24,6 +24,20 @@
#include <iostream> #include <iostream>
#include"MatrixGraph.h" #include"MatrixGraph.h"
using namespace std; using namespace std;
int main() { int main() {
MatrixGraph<int> graph = new MatrixGraph<int>();
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; return 0;
} }