bate's blog

調べたこと実装したことなどを取りとめもなく書きます。

2次元配列の実装

operator[]を実装どうすれば二次元になるのかしらん。

#include <iostream>
using namespace std;

template< typename T >
class TMatrix
{
private:
	T** m_elements;

	size_t m_row;
	size_t m_column;

public:
	TMatrix()
	{ }
	TMatrix( size_t row, size_t column )
	: m_elements(0), m_row( row ), m_column( column )
	{
		m_elements = new T*[m_row];
		for( int i = 0; i < (int)m_row; ++i )
			m_elements[i] = new T[m_column];
		for( int i = 0; i < (int)m_row; ++i )
			for( int j = 0; j < (int)m_column; ++j )
				m_elements[i][j] = 0;
	}
	TMatrix( T** array, size_t row, size_t column )
	: m_elements( array ), m_row( row ), m_column( column )
	{
		/*
		m_elements = array;
		m_row = row;
		m_column = column;
		*/
	}

	~TMatrix()
	{
		delete [] *m_elements;
		delete [] m_elements;
	}

	T GetMatrix( size_t index_1, size_t index_2 );
	void GetRow( size_t index, T *r_out );
	void GetColumn( size_t index, T *c_out );
	void SetMatrix( size_t index_1, size_t index_2, T input )
	{
		m_elements[index_1][index_2] = input;
	}
	void SetMatrix( T **array, size_t row, size_t column )
	{
		m_elements = array;
		m_row = row;
		m_column = column;
	}
	void Disp()
	{
		for( int i = 0; i < (int)m_row; ++i )
		{
			for( int j = 0; j < (int)m_column; ++j )
				cout << m_elements[i][j] << " ";
			cout << endl;
		}
	}
};


int main()
{
	// 行と列の数を入力
	int row=0, column=0;
	cout << "行の数を入力 >";
	cin >> row;
	cout << "列の数を入力 >";
	cin >> column;

	TMatrix<int> mat( row, column );
	mat.Disp();
	cout << endl;
	mat.SetMatrix( 0, 0, 1 );
	mat.Disp();

	return 0;
}
広告を非表示にする