1. 程式人生 > >C++模板程式設計實現二維陣列

C++模板程式設計實現二維陣列

陣列在C語言裡面經常使用,有一個缺陷就是必須在定義的時候就指定大小,一旦申請後這片區域就不能動態的擴充套件。但是很多情況下我們並不知道大小是多少,於是就需要動態分配記憶體來儲存。這裡僅僅是一個小例,希望可以起到拋磚引玉的作用。

為什麼使用模板?使用模板的通用性很強,陣列可能是int型別,也可能是bool型別……,使用模板就避免了為每一種型別去量身定製一套相同的功能。我想,這也是C++模板的初衷吧。

直接上程式碼:

template<class T, int row=0, int column=0>
class CMyArray
{
public:
	CMyArray()
		:m_pData(NULL)
		,m_nRow(row)
		,m_nColumn(column)
	{
		if ( m_nRow>0 && m_nColumn>0 )
			Allocate();
	}
	~CMyArray()
	{
		Free();
	}
	bool Resize(const int nRow, const int nColumn)
	{
		if ( nRow<=0 || nColumn<=0 )
			return false;
		m_nRow		= nRow;
		m_nColumn	= nColumn;
		Allocate();
		return true;
	}
	T GetAt(const int nRow, const int nColumn)
	{
		if ( nRow>=m_nRow || nColumn>=m_nColumn )
			return T();
		return *(m_pData+nRow*m_nColumn+nColumn);
	}
	void SetAt(const int nRow, const int nColumn, const T& data)
	{
		if ( nRow>=m_nRow || nColumn>=m_nColumn )
			return ;
		*(m_pData+nRow*m_nColumn+nColumn) = data;
	}
protected:
	void Allocate()
	{
		Free();
		m_pData = (T*)malloc(m_nRow*m_nColumn*sizeof(T));
	}
	void Free()
	{
		if ( m_pData )
		{
			free(m_pData);
			m_pData = NULL;
		}
	}
private:
	T*	m_pData;
	int	m_nRow;
	int m_nColumn;
};
buffer裡面儲存著這片連續記憶體空間的地址,對於這個區域的操作(釋放/申請),最好是在一個函式裡面進行,以免在多執行緒時出現記憶體讀寫錯誤。(多執行緒時,我們只需要對這個函式裡面加鎖就可以了)。

後記:

對於多維陣列,還可以擴充套件。效能方面這裡是沒有考慮的,如果需要申請的記憶體小於等於當前記憶體時,完全可以不進行釋放/申請過程。