Make implementation follow assignment rules

From what I could find, the rules of the assignment seem to be:

1. Restrict oneself to at most *one* O(log(N)) call, and otherwise use
   constant time operations on the map.
2. Don't use more operations than strictly necessary on `K` and `V`.
3. Prefer simplicity to performance.

I think my solution would fare well under those constraints.
This commit is contained in:
Bruno BELANYI 2024-08-24 20:19:32 +01:00
parent c41d1b2922
commit 08f2364c50

View file

@ -15,26 +15,45 @@ public:
if (!(begin < end)) if (!(begin < end))
return; return;
auto const end_val = (*this)[end]; auto it = underlying_.upper_bound(end);
underlying_.erase(underlying_.lower_bound(begin), auto const end_val = at_upper_bound(it);
underlying_.upper_bound(end));
if (!((*this)[begin] == val)) bool insert_begin = !(val == init_);
underlying_.insert({begin, val});
if (!((*this)[end] == end_val)) while (it != underlying_.begin()) {
underlying_.insert({end, end_val}); it = std::prev(it);
auto begin_found = it->first < begin;
if (begin_found) {
insert_begin = !(val == it->second);
break;
}
if (it != underlying_.end())
// Account for up-coming `std::prev` with `++`
underlying_.erase(it++);
}
if (insert_begin)
it = underlying_.insert(it, {begin, val});
// Get the proper upper-bound for `end`
it = (it == underlying_.end()) ? it : std::next(it);
if (!(at_upper_bound(it) == end_val))
underlying_.insert(it, {end, end_val});
} }
V const& operator[](K const& key) const { V const& operator[](K const& key) const {
auto it = underlying_.upper_bound(key); return at_upper_bound(underlying_.upper_bound(key));
if (it == underlying_.begin())
return init_;
return std::prev(it)->second;
} }
// Used in testing // Used in testing
friend class ::IntervalMapTest; friend class ::IntervalMapTest;
private: private:
V const& at_upper_bound(std::map<K, V>::const_iterator it) const {
if (it == underlying_.begin())
return init_;
return std::prev(it)->second;
}
V init_; V init_;
std::map<K, V> underlying_{}; std::map<K, V> underlying_{};
}; };