Skip to content

Commit 4e68ce1

Browse files
committed
add delete_key to hash tablewq
1 parent d59166c commit 4e68ce1

File tree

2 files changed

+30
-1
lines changed

2 files changed

+30
-1
lines changed

include/hash_table.h

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919

2020
#include <stdint.h>
2121
#include <limits.h>
22+
#include <stdexcept>
2223
#include "double_linked_list.h"
2324
#include "hash_multi.h"
2425

@@ -94,6 +95,26 @@ namespace alg
9495
}
9596
return false;
9697
}
98+
99+
/**
100+
* delete by key
101+
*/
102+
bool delete_key(uint32_t key)
103+
{
104+
// hash the key using a hash function.
105+
uint32_t hash = multi_hash(m_multi, key);
106+
107+
HashKV * kv, *nkv;
108+
list_for_each_entry_safe(kv,nkv,&m_slots[hash], node) {
109+
if (kv->key == key) {
110+
list_del(&kv->node);
111+
delete kv;
112+
return true;
113+
}
114+
}
115+
116+
return false;
117+
}
97118

98119
// const version of operator []
99120
const T& operator[] (uint32_t key) const
@@ -127,7 +148,7 @@ namespace alg
127148

128149
void clear()
129150
{
130-
struct HashKV * kv, *nkv;
151+
HashKV * kv, *nkv;
131152
for (uint32_t i=0;i<m_size;i++) {
132153
list_for_each_entry_safe(kv,nkv,&m_slots[i], node){
133154
list_del(&kv->node);

src/hash_table_demo.cpp

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,5 +24,13 @@ int main()
2424
printf("getting %d->%d\n", i, ht[i]);
2525
}
2626

27+
for(i = 0; i < MAX_ELEMENTS; i++ ){
28+
printf("deleting %d\n", ht.delete_key(i));
29+
}
30+
31+
for(i = 0; i < MAX_ELEMENTS; i++ ){
32+
printf("testing %d->%s\n", i, ht.contains(i)?"true":"false");
33+
}
34+
2735
return 0;
2836
}

0 commit comments

Comments
 (0)