Logo Data Structures and Algorithms with Object-Oriented Design Patterns in C++
next up previous contents index

Two-Dimensional Array Implementation

 

In this section we illustrate the implementation of a multi-dimensional array by giving the code for a generic two-dimensional array class, Array2D<T>, which is derived from the Array<T> class discussed in Section gif. The declaration of the Array2D<T> class template is shown in Program gif.

   program4055
Program: Array2D<T> and Array2D<T>::Row Class Definitions

Objects of the Array2D<T> class contain three member variables--numberOfRows, numberOfColumns, and array. The first two record the dimensions of the array. The last is an instance of the one-dimension array object discussed in Section gif.

The definitions of the Array2D<T> class member functions are given in Program gif. The constructor takes two arguments, m and n, which are the desired dimensions of the array. It calls the Array<T> class constructor to build a one-dimensional array of size mn. Using the result from Section gif, it can be shown that the running time for the Array2D<T> constructor is tex2html_wrap_inline61161.

   program4087
Program: Array2D<T> Class Member Functions

The Select function takes two arguments, i and j, and returns a reference to the tex2html_wrap_inline61089 element of the array. In the previous section we saw that the running time for the array subscripting calculation in an k-dimensional array is O(k). For a two-dimensional array, k=2. Therefore, the running time for the subscript calculation is O(2)=O(1).


next up previous contents index

Bruno Copyright © 1997 by Bruno R. Preiss, P.Eng. All rights reserved.