#include <iostream>
using namespace std;
template <typename T>
class Graph
{
public:
Graph(const int init = 5);
~Graph();
void addVertex(T* t);
void addEdge(int start, int end);
void printVertex();
void printMat();
private:
int n;
int nVerts;
T** vertsList;
int** adjMat;
};
template <typename T>
Graph<T>::Graph(const int init)
{
this->n = init;
this->nVerts = 0;
this->vertsList = new T* [this->n];
for (int i = 0; i < this->n; ++i)
{
this->vertsList[i] = new T(T());
}
this->adjMat = new int* [this->n];
for (int i = 0; i < this->n; ++i)
{
this->adjMat[i] = new int[this->n];
for (int j = 0; j < this->n; ++j)
{
this->adjMat[i][j] = 0;
}
}
}
template <typename T>
Graph<T>::~Graph()
{
delete[] vertsList;
delete[] adjMat;
cout << endl << "~Graph() delete" << endl;
}
template <typename T>
void Graph<T>::addVertex(T* t)
{
if (this->n < nVerts) throw " ";
this->vertsList[nVerts++] = t;
}
template <typename T>
void Graph<T>::addEdge(int start, int end)
{
this->adjMat[start][end] = 1;
this->adjMat[end][start] = 1;
}
template <typename T>
void Graph<T>::printVertex()
{
for (int i = 0; i < this->n; ++i)
{
cout << *this->vertsList[i] << " ";// ostream& operator<<(ostream& out, T& t)
}
cout << endl;
}
template <typename T>
void Graph<T>::printMat()
{
cout << " "; this->printVertex();
for (int i = 0; i < this->n; ++i)
{
cout << *this->vertsList[i] << " ";
for (int j = 0; j < this->n; ++j)
{
cout <<this->adjMat[i][j] << " ";
}
cout << endl;
}
}
int main()
{
Graph<char> g(6);
char a('A');
char b('B');
char c('C');
char d('D');
char e('E');
char f('F');
g.addVertex(&a);
g.addVertex(&b);
g.addVertex(&c);
g.addVertex(&d);
g.addVertex(&e);
g.addVertex(&f);
g.addEdge(0,1);
g.addEdge(0, 2);
g.addEdge(0, 3);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
cout << "Vertex :" << endl;
g.printVertex(); cout << endl;
cout << "邻接矩阵 :" << endl;
g.printMat();
cout << endl << "ok" << endl;
return 0;
}
C++实现 图Graph --- 邻接矩阵
最新推荐文章于 2024-06-06 16:43:44 发布