c++实现邻接矩阵

#include<iostream>
using namespace std;

const int MAX = 10; //最大顶点数
//typedef char vertex_type; //顶点类型
//typedef int edge_weight_type; //边上权值类型

template<class vertex_type, class edge_weight_type>
class Graph
{
private:
	int vertex_num; //顶点数
	int edge_num; //边数
	vertex_type vex[MAX]; //存放顶点的数组
	edge_weight_type arc[MAX][MAX]; //邻接矩阵

public:
	Graph(); //构造函数
	//~Graph(); //析构函数
	int locate(char ch); //定位
	void print_graph(); //打印
};


// 定位
template<class vertex_type, class edge_weight_type>
int Graph<vertex_type, edge_weight_type>::locate(char ch)
{
	int i = 0;
	for (i = 0; i < this->vertex_num; i++)
	{
		if (this->vex[i] == ch)
		{
			break;
		}
	}
	return i;
}


//构造函数
template<typename vertex_type, typename edge_weight_type>
Graph<typename vertex_type, typename edge_weight_type>::Graph()
{
	int i = 0, j = 0, k = 0, weight = 0;
	cout << "输入顶点数和边数:" << endl;
	cin >> this->vertex_num >> this->edge_num;

	//存储顶点
	cout << "请输入顶点:" << endl;
	for (i = 0; i < this->vertex_num; i++)
	{
		cin >> this->vex[i];
	}

	//初始化邻接矩阵
	for (i = 0; i < this->vertex_num; i++)
	{
		for (j = 0; j < this->vertex_num; j++)
		{
			this->arc[i][j] = 0;
		}
	}

	cout << "输入两个顶点及其权值:" << endl;
	for (k = 0; k < this->edge_num; k++)
	{
		char first, second;
		cin >> first >> second >> weight;
		i = this->locate(first);
		j = this->locate(second);
		
		this->arc[i][j] = weight;
		this->arc[j][i] = weight;
	}
}

//打印
template<typename vertex_type, typename edge_weight_type>
void Graph<typename vertex_type, typename edge_weight_type>::print_graph()
{
	cout << "邻接矩阵为:" << endl;
	for (int i = 0; i < this->vertex_num; i++)
	{
		for (int j = 0; j < this->vertex_num; j++)
		{
			cout << "\t" << this->arc[i][j];
		}
		cout << endl;
	}
}

int main()
{
	Graph<char, int> g;
	g.print_graph();
	system("pause");
 	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值