Grafalgo
Library of useful data structures and algorithms
/Users/jst/src/grafalgo/cpp/dataStructures/hash/HashMap.cpp
Go to the documentation of this file.
00001 
00009 #include "HashMap.h"
00010 
00011 namespace grafalgo {
00012 
00016 HashMap::HashMap(int n1) : Adt(n1) { makeSpace(n()); };
00017         
00019 HashMap::~HashMap() { freeSpace(); }
00020 
00024 void HashMap::makeSpace(int size) {
00025         try {
00026                 values = new int[size+1];
00027                 ht = new HashTbl(size); kvx = new SetPair(size);
00028         } catch (std::bad_alloc e) {
00029                 stringstream ss;
00030                 ss << "HashMap::makeSpace: insufficient space for "
00031                    << size << "index values";
00032                 string s = ss.str();
00033                 throw OutOfSpaceException(s);
00034         }
00035         nn = size;
00036 }
00037 
00039 void HashMap::freeSpace() { delete [] values; delete ht; delete kvx; }
00040 
00045 void HashMap::resize(int size) {
00046         freeSpace();
00047         try { makeSpace(size); } catch(OutOfSpaceException e) {
00048                 string s; s = "HashMap::resize::" + e.toString(s);
00049                 throw OutOfSpaceException(s);
00050         }
00051 }
00052 
00057 void HashMap::expand(int size) {
00058         if (size <= n()) return;
00059         HashMap old(this->n()); old.copyFrom(*this);
00060         resize(size); this->copyFrom(old);
00061 }
00062 
00064 void HashMap::clear() {
00065         while (firstPair() != 0) remove(key(firstPair()));
00066 }
00067 
00069 void HashMap::copyFrom(const HashMap& src) {
00070         if (&src == this) return;
00071         if (src.n() > n()) resize(src.n());
00072         else clear();
00073         for (index x = src.firstPair(); x != 0; x = src.nextPair(x))
00074                 put(src.key(x), src.val(x));
00075 }
00076 
00077 // Construct string listing the key,value pairs in the map
00078 string& HashMap::toString(string& s) const {
00079         stringstream ss; ss << "{";
00080         bool isFirst = true;
00081         for (int kvi = kvx->firstIn(); kvi != 0; kvi = kvx->nextIn(kvi)) {
00082                 if (isFirst) isFirst = false;
00083                 else ss << " ";
00084                 ss << "(" << key(kvi) << "," << val(kvi) << ")";
00085         }
00086         ss << "}"; s = ss.str(); return s;
00087 }
00088 
00089 } // ends namespace
 All Classes Files Functions Variables Typedefs Friends