From df2b780c0faef427e78b39f4ac2c5c275d70e812 Mon Sep 17 00:00:00 2001 From: Adrian Kummerländer Date: Tue, 4 Feb 2014 18:51:17 +0100 Subject: Implemented remove member method --- trie.cc | 43 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 39 insertions(+), 4 deletions(-) diff --git a/trie.cc b/trie.cc index 1da306c..130e2db 100644 --- a/trie.cc +++ b/trie.cc @@ -21,14 +21,42 @@ class Trie { inline void add( key_list& path, - typename key_list::const_iterator curr + typename key_list::const_iterator currStep ) { - if ( curr != path.end() ) { + if ( currStep != path.end() ) { Trie& trie( - this->children_[*curr] + this->children_[*currStep] ); - trie.add(path, ++curr); + trie.add(path, ++currStep); + } + } + + inline void remove(key_list path) { + this->remove(path, path.begin()); + } + + inline void remove( + key_list& path, + typename key_list::const_iterator currStep + ) { + if ( currStep != path.end() ) { + typename std::map::iterator matchingTrie( + this->children_.find(*currStep) + ); + + if ( matchingTrie != this->children_.end() ) { + typename key_list::const_iterator nextStep( + ++currStep + ); + + if ( (*matchingTrie).second.children_.empty() || + nextStep == path.end() ) { + this->children_.erase(matchingTrie); + } else { + (*matchingTrie).second.remove(path, nextStep); + } + } } } @@ -73,6 +101,13 @@ int main() { test.add({2, 1, 1}); assert(test.resolve({1, 2}).second != nullptr); + assert(test.resolve({1, 2, 3}).second != nullptr); assert(test.resolve({1, 2, 4}).second != nullptr); assert(test.resolve({3}).second == nullptr); + + test.remove({1, 2}); + + assert(test.resolve({1, 2, 4}).second == nullptr); + assert(test.resolve({1, 2, 3}).second == nullptr); + assert(test.resolve({1, 2}).second == nullptr); } -- cgit v1.2.3