Skip to content
Snippets Groups Projects
Commit ebf8c727 authored by hcasse's avatar hcasse
Browse files

data: added HashMap::fetch() and support in HashTable.

parent acc151e4
Branches
No related tags found
No related merge requests found
......@@ -47,6 +47,9 @@ public:
inline void clear(void) { _tab.clear(); }
inline void add(const K& key, const T& val) { _tab.add(pair(key, val)); }
inline T& fetch(const K& k)
{ auto *n = _tab.get(key(k)); if(n != nullptr) return n->snd; return _tab.add(pair(k, T()))->snd; }
// Map concept
inline Option<T> get(const K& k) const
{ auto *r = _tab.get(key(k)); if(r) return some(r->snd); else return none; }
......
......@@ -41,6 +41,7 @@ private:
T data;
};
protected:
node_t *find(const T& key) const {
int i = H::computeHash(key) % _size;
for(node_t *node = _tab[i], *prev = 0; node; prev = node, node = node->next)
......@@ -60,6 +61,8 @@ private:
return 0;
}
private:
node_t *make(const T& data) {
int i = H::computeHash(data) % _size;
node_t *node = new(A::allocate(sizeof(node_t))) node_t(data);
......@@ -152,7 +155,7 @@ public:
}
}
void add(const T& data) { make(data); }
T *add(const T& data) { return &make(data)->data; }
inline self_t& operator+=(const T& x) { add(x); return *this; }
......@@ -208,6 +211,9 @@ public:
}
inline self_t& operator=(const HashTable<T, H>& c) { copy(c); return *this; }
inline T *get(const T& key)
{ node_t *node = find(key); return node ? &node->data : 0; }
# ifdef ELM_STAT
int minEntry(void) const { int m = count(0); for(int i = 1; i < _size; i++) m = min(m, count(i)); return m; }
int maxEntry(void) const { int m = count(0); for(int i = 1; i < _size; i++) m = max(m, count(i)); return m; }
......
......@@ -164,6 +164,15 @@ namespace elm {
* @param size Table size (default to 211).
*/
/**
* @fn T& HashMap::fetch(const K& k);
* Get a reference to the data stored with the key k. If no data is already
* associated with key k, an entry and corresponding data are created
* and returns a reference to it.
* @param k Key of looked data.
* @return Reference to data associated with key.
*/
/**
* @fn bool HashMap::isEmpty(void) const;
* Test if the map is empty.
......
......@@ -86,6 +86,7 @@ TEST_BEGIN(hashtable)
m[1];
cm[1];
m[1] = 1;
m.fetch(1);
}
}
......@@ -221,7 +222,7 @@ TEST_BEGIN(hashtable)
bool failed = false;
for(int i = 0; i < 100; i++) {
string k = _ << i << (-i);
Option<int> o = map2.get(k);
auto o = map2.get(k);
if(!o || *o != i) {
failed = true;
break;
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment