#include "uvmap.h" #include "uviterator.h" #include // Owen Astrachan // 11/8/95 static const int NOT_FOUND = -1; template UVMap::UVMap(int size) : myList(size), myNumElts(0) // postcondition: all fields constructed, initialized { // work done in initializer list } template UVMap::~UVMap() { // nothing to do, vector does itself } template void UVMap::CheckSize() // postcondition: there is room to add an element in private vector { if (myNumElts >= myList.Length()) { myList.SetSize(myList.Length() * 2); } } template Value & UVMap::GetValue(const Key & key) // postcondition: returns value associated with key in map // exception: if key not in map, error printed, program halted { int index = Find(key); // find location if (index != NOT_FOUND) { return myList[index].second; } cerr << "Error in GetValue, aborting execution" << endl; abort(); } template const Value & UVMap::GetValue(const Key & key) const // postcondition: returns value associated with key in map // exception: if key not in map, error printed, program halted { int index = Find(key); if (index != NOT_FOUND) { return myList[index].second; } cerr << "Error in GetValue (const), aborting execution" << endl; abort(); } template void UVMap::Apply(void (*Func) (Pair & p)) // postcondition: Func() applied to all map elements { int k; for(k=0; k < myNumElts; k++) { (*Func)(myList[k]); } } template void UVMap::Apply(MapBase & obj) // postcondition: obj.Function() applied to all map elements { int k; for(k=0; k < myNumElts; k++) { obj.Function(myList[k].first,myList[k].second); } } template bool UVMap::IncludesKey(const Key & key) const // postcondition: returns true if key in map, otherwise returns false { return Find(key) != NOT_FOUND; } template int UVMap::Find(const Key & key) const // postcondition: returns index of key in private vector // returns NOT_FOUND if key NOT in vector { int k; for(k=0; k < myNumElts; k++) { if (myList[k].first == key) { return k; } } return NOT_FOUND; } template void UVMap::GetValue(Pair & pair) // postcondition: pair = pair associated with key (pair.first) in map // if key NOT in map, no value assigned { int index = Find(pair.first); if (index != NOT_FOUND) { pair = myList[index]; } } template void UVMap::Insert(const Pair & pair) // precondition: pair.first key NOT stored in map // postcondition: pair is added to map (maps pair.first -> pair.second) { int index = Find(pair.first); if (index == NOT_FOUND) { CheckSize(); myList[myNumElts] = pair; myNumElts++; } } template void UVMap::Delete(const Key & key) // precondition: pair.first key stored in map // postcondition: Key is deleted from map { int index = Find(key); if (index != NOT_FOUND) { --myNumElts; myList[index] = myList[myNumElts]; } } template void UVMap::Insert(const Key & key, const Value & val) { Insert(Pair(key,val)); } template Iterator > * UVMap::MakeIterator() // postcondition: returns dynamically allocated iterator { Iterator > * temp = new UVMapIterator >(myList,myNumElts); return temp; }