aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdrian Kummerländer2014-02-04 18:51:17 +0100
committerAdrian Kummerländer2014-02-04 18:51:17 +0100
commitdf2b780c0faef427e78b39f4ac2c5c275d70e812 (patch)
tree05966b68f205e8ec17ea41e313ba71142669005f
parent24dee38d72ffa8b0a2515dc40c00a43b46526438 (diff)
downloadTrie-df2b780c0faef427e78b39f4ac2c5c275d70e812.tar
Trie-df2b780c0faef427e78b39f4ac2c5c275d70e812.tar.gz
Trie-df2b780c0faef427e78b39f4ac2c5c275d70e812.tar.bz2
Trie-df2b780c0faef427e78b39f4ac2c5c275d70e812.tar.xz
Trie-df2b780c0faef427e78b39f4ac2c5c275d70e812.zip
Implemented remove member method
-rw-r--r--trie.cc43
1 files 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<Key, Trie>::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);
}