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

CSE 143/AC : 6 July 2000


ADT Example: Vector : Exercise solutions

class Item { public: Item(); bool equals(Item& other); bool lessThan(Item& other); private: // hidden }; const int MAX_VECTOR_SIZE = 50; const int INVALID_INDEX = -1; 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; -1 if not found int indexOf(Item item); private: Item contents[MAX_VECTOR_SIZE]; int size; }; #ifndef _SORTED_ // Unsorted version int Vector::indexOf(Item item) { for (int i=0; i<length(); i++) { if (item.equals(get(i))) return i; } return INVALID_INDEX; } #else // Sorted version 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; } #endif

Last modified: Thu Jul 6 13:51:34 PDT 2000