Last active
March 26, 2022 17:37
-
-
Save dgodfrey206/6738f56524c8a33c9389 to your computer and use it in GitHub Desktop.
A 2-dimensional array class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdexcept> | |
// uses the Array<T> class | |
template <class T> | |
class Array2D | |
{ | |
protected: | |
unsigned int numberOfRows, numberOfColumns; | |
Array<T> array; | |
public: | |
class Row | |
{ | |
Array2D& array2D; | |
unsigned int const row; | |
public: | |
Row(Array2D& _array2D, unsigned int _row) | |
: array2D(_array2D) | |
, row(_row) | |
{ } | |
T& operator[](unsigned int column) const | |
{ return array2D.Select(row, column); } | |
}; | |
Array2D(unsigned int, unsigned in); | |
T& Select(unsigned int, unsigned int); | |
Row operator[](unsigned int); | |
}; | |
template <class T> | |
Array2D<T>::Array2D(unsigned int n, unsigned int m) | |
: numberOfRows(n) | |
, numberOfColumns(m) | |
, array(n * m) | |
{ } | |
template <class T> | |
T& Array2D<T>::Select(unsigned int i, unsigned int j) | |
{ | |
if (i >= numberOfRows) | |
throw std::out_of_range("invalid row"); | |
if (i >= numberOfColumns) | |
throw std::out_of_range("invalid column"); | |
return array[i * numberOfColumns + j]; | |
} | |
template <class T> | |
typename Array2D<T>::Row Array2D<T>::operator[](unsigned int row) | |
{ return Row(*this, row); } | |
int main() | |
{ | |
Array2D<int> array(2, 2); | |
array[0][0]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment