Grafalgo
Library of useful data structures and algorithms
|
00001 00009 #include "IdMap.h" 00010 00011 namespace grafalgo { 00012 00016 IdMap::IdMap(int n1) : Adt(n1) { makeSpace(n()); }; 00017 00019 IdMap::~IdMap() { freeSpace(); } 00020 00024 void IdMap::makeSpace(int size) { 00025 try { 00026 ht = new HashTbl(size); 00027 ids = new SetPair(size); 00028 } catch (std::bad_alloc e) { 00029 stringstream ss; 00030 ss << "IdMap::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 IdMap::freeSpace() { delete ht; delete ids; } 00040 00045 void IdMap::resize(int size) { 00046 freeSpace(); 00047 try { makeSpace(size); } catch(OutOfSpaceException e) { 00048 string s; s = "IdMap::resize:" + e.toString(s); 00049 throw OutOfSpaceException(s); 00050 } 00051 } 00052 00057 void IdMap::expand(int size) { 00058 if (size <= n()) return; 00059 IdMap old(this->n()); old.copyFrom(*this); 00060 resize(size); this->copyFrom(old); 00061 } 00062 00064 void IdMap::clear() { 00065 while (firstId() != 0) dropPair(getKey(firstId())); 00066 } 00067 00069 void IdMap::copyFrom(const IdMap& source) { 00070 if (&source == this) return; 00071 if (source.n() > n()) resize(source.n()); 00072 else clear(); 00073 for (index x = source.firstId(); x != 0; x = source.nextId(x)) 00074 addPair(source.getKey(x),x); 00075 } 00076 00082 int IdMap::addPair(uint64_t key) { 00083 index x = ids->firstOut(); 00084 if (x == 0 || !ht->insert(key,x)) return 0; 00085 ids->swap(x); 00086 return x; 00087 } 00088 00095 int IdMap::addPair(uint64_t key, int id) { 00096 if (ids->isIn(id) || !ht->insert(key,id)) return 0; 00097 ids->swap(id); 00098 return id; 00099 } 00100 00105 void IdMap::dropPair(uint64_t key) { 00106 index x = ht->remove(key); 00107 if (ids->isIn(x)) ids->swap(x); 00108 } 00109 00113 string& IdMap::toString(string& s) const { 00114 stringstream ss; ss << "{"; 00115 for (index x = firstId(); x != 0; x = nextId(x)) { 00116 if (x != firstId()) ss << " "; 00117 ss << getKey(x) << ":" << x; 00118 } 00119 ss << "}"; s = ss.str(); return s; 00120 } 00121 00122 } // ends namespace