#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;
}
c++实现邻接矩阵
最新推荐文章于 2025-09-25 09:10:34 发布
561

被折叠的 条评论
为什么被折叠?



