trie_impl.hpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. //
  2. // trie_impl.hpp
  3. // trie
  4. //
  5. // Created by Sam Jaffe on 6/16/17.
  6. //
  7. #pragma once
  8. #include "trie.hpp"
  9. #include "trie_iterator.hpp"
  10. template <typename K, typename V, typename C>
  11. trie<K, V, C>::trie(mapped_type const & value)
  12. : value_(value) {
  13. }
  14. // n := total elements
  15. // d := average depth
  16. // Stack: O(1)
  17. // Operations: O(n*d)
  18. template <typename K, typename V, typename C>
  19. trie<K, V, C>::trie(trie const & other) {
  20. for (const_iterator it = other.begin(), end = other.end(); it != end; ++it) {
  21. insert(it.keys, *it);
  22. }
  23. }
  24. template <typename K, typename V, typename C>
  25. auto trie<K, V, C>::operator=(mapped_type const & value) -> self_t & {
  26. value_ = value;
  27. return *this;
  28. }
  29. template <typename K, typename V, typename C>
  30. auto trie<K, V, C>::operator=(trie const & other) -> self_t & {
  31. for (const_iterator it = other.begin(), end = other.end(); it != end; ++it) {
  32. insert(it.keys, *it);
  33. }
  34. return *this;
  35. }
  36. template <typename K, typename V, typename C>
  37. template <typename KS, typename>
  38. auto trie<K, V, C>::operator[](KS const & keys) -> self_t & {
  39. self_t * rec = this;
  40. for ( key_type const & key : keys ) {
  41. rec = &(*rec)[key];
  42. }
  43. return *rec;
  44. }
  45. template <typename K, typename V, typename C>
  46. auto trie<K, V, C>::operator[](key_type const & key) -> self_t & {
  47. auto it = impl_.lower_bound(key);
  48. if ( it == impl_.end() || key_compare()(key, it->first) ) {
  49. it = impl_.emplace_hint(it, key, make_value<self_t>());
  50. }
  51. return *(it->second);
  52. }
  53. template <typename K, typename V, typename C>
  54. auto trie<K, V, C>::operator[](std::initializer_list<key_type> keys) -> self_t & {
  55. self_t * rec = this;
  56. for ( key_type const & key : keys ) {
  57. rec = &(*rec)[key];
  58. }
  59. return *rec;
  60. }
  61. template <typename K, typename V, typename C>
  62. template <typename KS>
  63. auto trie<K, V, C>::insert(KS const & keys, mapped_type const & value) -> void {
  64. operator[](keys) = value;
  65. }
  66. template <typename K, typename V, typename C>
  67. auto trie<K, V, C>::insert(std::initializer_list<key_type> keys, mapped_type const & value) -> void {
  68. operator[](keys) = value;
  69. }
  70. template <typename K, typename V, typename C>
  71. auto trie<K, V, C>::insert(key_type const & key, mapped_type const & value) -> std::pair<iterator, bool> {
  72. auto it = impl_.lower_bound(key);
  73. if ( it == impl_.end() || key_compare()(key, it->first) ) {
  74. return { impl_.emplace_hint(it, key, make_value<self_t>(value)), true };
  75. }
  76. return { it, false };
  77. }