template<Comparable KEY, typename VALUE> classBinarySearchSymbolTable { public: voidput(KEY key, VALUE value){ int i = rank(key); if (i < keys_.size() && keys_[i] == key) { values_[i] = value; return; } keys_.insert(keys_.begin() + i, key); values_.insert(values_.begin() + i, value); }
std::optional<VALUE> get(KEY key){ if (is_empty()) return std::nullopt; int i = rank(key); if (i < keys_.size() && keys_[i] == key) { return values_[i]; } return std::nullopt; }
voidremove(KEY key){ if (is_empty()) return; int i = rank(key); if (i < keys_.size() && keys_[i] == key) { keys_.erase(keys_.begin() + i); values_.erase(values_.begin() + i); } }
// returns the number of keys in this symbol table strictly less than key. intrank(KEY key){ int left = 0, right = keys_.size() - 1; while (left <= right) { int mid = left + (right - left) / 2; // prevent integer overflow if (key < keys_[mid]) { right = mid - 1; } elseif (key > keys_[mid]) { left = mid + 1; } else { return mid; } } return left; }
std::optional<KEY> min(){ if (is_empty()) return std::nullopt; return keys_.front(); }
std::optional<KEY> max(){ if (is_empty()) return std::nullopt; return keys_.back(); }
std::optional<KEY> select(int k){ if (k < 0 || k >= keys_.size()) return std::nullopt; return keys_[k]; }