ClassS04CS141/Prog1

ClassS04CS141 | ClassS04CS141 | recent changes | Preferences

Showing revision 5
Difference (from revision 5 to revision 5) (minor diff, author diff)
(The revisions are identical or unavailable.)

Part 1:

Here is the interface I want you to use for the array class. If you are uncomfortable with templates, first implement the class assuming the VALUE type is "int".

// Array.h
#ifndef _ARRAY_H
#define _ARRAY_H

// growable array, indexed by non-negative integers 0,1,2,...
//
// VALUE's are passed around as parameters and copy-assigned freely
// VALUE must be able to be assigned a value of 0 (numeric or pointer)

template <class VALUE>
class Array {
  
  VALUE *table;
  int max_referenced;
  int table_size;

  void grow();                  // replace the table with one twice as large
                                // copy the old contents into the new table
 public:
  Array();                      // start with a small table full of zeros
  VALUE & operator[](int i);    // returns a reference to the i'th table element
                                // grows the table if necessary
                                // newly allocated elements start out 0
  ~Array();                     // destructor
  int size();                   // returns size = 1+largest index referenced so far
};

#endif

Here is a simple test routine:

// test_array.cc
#include <iostream.h>

#include "Array.h"
#include "Array.cc"

main() {
  Array<int> h;
  
  h[1] = 2;
  h[2] = 4;
  h[3] = 6;

  for (int i = 0;  i < h.size(); ++i) {
    cout << h[i] << endl;
  }
}

Here is a simple Makefile:

test_array: test_array.o Array.o
        g++ -o test_array test_array.o Array.o

Array.o: Array.h Array.cc
        g++ -c Array.cc

Part 2:


ClassS04CS141 | ClassS04CS141 | recent changes | Preferences
This page is read-only | View other revisions | View current revision
Edited March 31, 2004 11:00 am by NealYoung (diff)
Search: