From c2ef54c044934a9825932cf510dc7b44dee88207 Mon Sep 17 00:00:00 2001 From: Andreas Kling Date: Sat, 13 Oct 2018 14:22:09 +0200 Subject: [PATCH] Add HashTable::remove() and fix a bug where ConstIterator would skip the first. --- AK/HashTable.h | 23 ++++++++++++++++++++--- AK/test.cpp | 28 ++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) diff --git a/AK/HashTable.h b/AK/HashTable.h index 59b89928098..4de631a582f 100644 --- a/AK/HashTable.h +++ b/AK/HashTable.h @@ -186,12 +186,12 @@ public: { if (!isEnd && !m_table.isEmpty() && !(m_bucketIterator != DoublyLinkedList::ConstIterator::universalEnd())) { #ifdef HASHTABLE_DEBUG - printf("bucket iterator init!\n"); + printf("const bucket iterator init!\n"); #endif const DoublyLinkedList& chain = m_table.m_buckets[0].chain; m_bucketIterator = chain.begin(); - - skipToNext(); + if (m_bucketIterator.isEnd()) + skipToNext(); } } @@ -207,6 +207,15 @@ public: Iterator find(const T&); ConstIterator find(const T&) const; + void remove(const T& value) + { + auto it = find(value); + if (it != end()) + remove(it); + } + + void remove(Iterator&); + private: Bucket& lookup(const T&); const Bucket& lookup(const T&) const; @@ -315,6 +324,14 @@ auto HashTable::find(const T& value) const -> ConstIterator return end(); } +template +void HashTable::remove(Iterator& it) +{ + ASSERT(!isEmpty()); + m_buckets[it.m_bucketIndex].chain.remove(it.m_bucketIterator); + --m_size; +} + template typename HashTable::Bucket& HashTable::lookup(const T& value) { diff --git a/AK/test.cpp b/AK/test.cpp index 5c97d0a70af..8840c86e5af 100644 --- a/AK/test.cpp +++ b/AK/test.cpp @@ -155,5 +155,33 @@ int main(int, char**) printInts(v); } + { + auto printInts = [] (const HashTable& h) { + printf("HashTable {\n size: %u\n capacity: %u\n elements: ", h.size(), h.capacity()); + for (auto i : h) + printf("%d ", i); + printf("\n}\n"); + }; + + HashTable h; + + h.set(10); + h.set(20); + h.set(30); + h.set(40); + h.set(50); + + h.dump(); + + printInts(h); + + h.remove(30); + printInts(h); + + h.set(30); + h.remove(30); + printInts(h); + } + return 0; }