C++实现 图Graph --- 邻接矩阵

#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;
}

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值