#include
using namespace std;
//无向图的邻接矩阵表示法
template
class map
{
public:
map(T _data[],int len);
~map();
void print();
private:
T* M; //顶点表
bool** arr; //邻接矩阵 -- 有边true 无边false 带权值的图可以用整型数组 数组中存放权值
int length; //记录元素数量
};
template
map::map(T _data[],int len)
{
//为表和矩阵开辟空间
length = len - 1; //数组中要留位置放结束符 '/0' 故长度比实际大1
M = new T[length];
arr = new bool* [length];
for (int i = 0; i < length; i++)
{
M[i] = _data[i];
arr[i] = new bool[length];
for (int j = 0; j < length; j++) { arr[i][j] = false; }
}
//设置顶点间的边
int quantity; //记录边的数量
cout << "输入边的数量:";
cin >> quantity;
//边数量异常
if (quantity < 0 || quantity > length * (length - 1) / 2) { cout << "边数量错误!" << endl; return; }
//开始创建边
for (int i = 0; i < quantity; i++)
{
cout << i + 1 <<" 请输入有边的两个顶点的位置:";
int k, z;
cin >> k;
cin >> z;
//应判断输入的坐标是否在数组中存在否则会引起数组越界 此处省略
//无向图的边是相互的所以从任意顶点到另一顶点都有边存在
arr[k][z] = true;
arr[z][k] = true;
}
}
template
map::~map()
{
if (M != nullptr) { delete M; M = nullptr; }
if (arr != nullptr)
{
for (int i = 0; i < length; i++)
{
delete[]arr[i];
arr[i] = nullptr;
}
arr = nullptr;
}
length = 0;
}
template //遍历顶点表和邻接矩阵
void map::print()
{
for (int i = 0; i < length; i++)
{
for (int j = 0; j < length; j++)
{
cout << arr[i][j] << " ";
}
cout << "tt" << M[i] << endl;
}
}