ClassS04CS141/Prog1Part1

ClassS04CS141 | ClassS04CS141 | recent changes | Preferences

No diff available--this is the first major revision. (no other diffs)

Part 1:

Use the files Array.h (specifying the interface) and the Makefile, below. Your job is to write the Array.cc file implementing the member functions of the Array class.

Here is an example of how the class will be used:


// 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;
  }
}

This class represents a "virtually infinite" array. The array h is declared without a predetermined size. The user of the array is free to access it at any non-negative integer index. For example, h[100], h[1000], etc. The implementation must grow the array as necessary to support this.

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". Then look at the CPlusPlusDocs page for information about templates.

You will need to use C++ references to implement the operator[] member function. If you've forgotten about references, check out the CPlusPlusDocs page for information about references.


// 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 Makefile:


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

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


ClassS04CS141 | ClassS04CS141 | recent changes | Preferences
This page is read-only | View other revisions
Last edited April 5, 2004 2:10 pm by Neal (diff)
Search: