[   ^ to index...   |   next -->   ]

CSE 143/AE : 6 July 2000


ADT example: Vector : exercise solutions

class Item { public: Item(); bool equals(Item& other); bool lessThan(Item& other); private: // some stuff }; const int MAX_VECTOR_SIZE = 40; class Vector { public: Vector(); bool isEmpty(); int length(); void insert(int position, Item item); Item delete(int position); Item get(int position); // Find the index of the given item; // return -1 if not in vector int indexOf(Item item); private: Item contents[MAX_VECTOR_SIZE]; int size; }; // CONSTRUCTOR Vector::Vector() { // We only need to initialize the size. It is fine if the // contents are uninitialized, because they do not contain // any valid data yet. size = 0; } // UNSORTED indexOf method int Vector::indexOf(Item item) { for (int i=0; i<length(); i++) { if (item.equals(get(i))) return i; } return INVALID_INDEX; } // SORTED indexOf method int Vector::indexOf(Item item) { for (int i=0; i<length(); i++) { if ( item.equals(get(i)) ) return i; else if ( item.lessThan(get(i)) ) break; } return INVALID_INDEX; }

Last modified: Thu Jul 6 13:58:14 PDT 2000