trimat.h

来自「分级聚类算法:包括k-mean max-dist min-dist 程序使用方」· C头文件 代码 · 共 178 行

H
178
字号
// TriMat.h: interface for the TriMat class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(_TRIMAT_H_)
#define _TRIMAT_H_

#include <iostream>
#include <cstdlib>
#include <iomanip>

using namespace std;

const int ELEMENTLIMIT = 32767;
const int ROWLIMIT = 255;

template <class T>
class TriMat  
{
	private:
		int * rowTable;
		T * M;
		int n;
	public:
		TriMat(int matSize);
		virtual ~TriMat();

		inline void SetElement(T item, int i, int j);
		inline T GetElement(int i, int j) const;

		void ReadMat(void);
		void PrintMat(void) const;
		int GetN(void) const;
		inline void FindAbsMin(T &a, int& i, int& j) const;
};

template <class T>
TriMat<T>::TriMat(int matSize)
{
	rowTable = NULL;
	M = NULL;

	n = matSize;
	if (n > 255)
	{
		cerr << "matrix size is more than 255" << endl;
		exit(1);
	}
	rowTable = new int[n];
	int temp, i;
	temp = n * (n + 1) / 2;
	M = new T[temp];

	for (i = 0; i < temp; i++)
	{
		M[i] = -1;
	}

	temp = 0;
	for (i = 0; i < n; i++)
	{
		rowTable[i] = temp;
		temp += n - i;
	}
}

template <class T>
TriMat<T>::~TriMat()
{
	if (rowTable != NULL)
	{
		delete[] rowTable;
		delete[] M;
	}
}

template <class T>
void TriMat<T>::SetElement(T item, int i, int j)// a[i, j]
{
	if ((i<0 || i>=n) || (j<0 || j>=n))
	{
		cerr << "index out of range" << endl;
		exit(1);
	}
	if (j < i)
	{
		int t;
		t = i;
		i = j;
		j = t;
	}
	M[rowTable[i] + j - i] = item;
}

template <class T>
T TriMat<T>::GetElement(int i, int j) const// a[i, j]
{
	if ((i<0 || i>=n) || (j<0 || j>=n))
	{
		cerr << "index out of range" << endl;
		exit(1);
	}
	if (j < i)
	{
		int t;
		t = i;
		i = j;
		j = t;
	}
	return M[rowTable[i] + j - i];
}

template <class T>
int TriMat<T>::GetN() const
{
	return n;
}

template <class T>
void TriMat<T>::ReadMat()
{
	T item;
	int i, j;

	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			cin >> item;
			SetElement(item, i, j);
		}
	}
}

template <class T>
void TriMat<T>::PrintMat() const
{
	int i, j;
	for (i = 0; i < n; i++)
	{
		for (j = 0; j < n; j++)
		{
			cout << setw(7) << GetElement(i, j);
		}
		cout << endl;
	}
}

template <class T>
void TriMat<T>::FindAbsMin(T &a, int& ai, int& aj) const
{
	int i, j;
	T temp;
	a = 32767;
	ai = 0;
	aj = 1;
	for (i = 0; i < n; i++)
	{
		for (j = i+1; j < n; j++)
		{
			temp = GetElement(i, j);
			if (temp <= 0)
			{
				continue;
			}
			if (a > temp)
			{
				a = temp;
				ai = i;
				aj = j;
			}
		}
		cout << "a[" << ai << ", " << aj << "] = " << a << endl;
	}
}

#endif // !defined(_TRIMAT_H_)

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?