I need to implement a step function (i.e. piecewise constant). There are a few requirements that it will need to have.
- It will have to be evaluated repeatedly at random locations, then evaluated sequentially over an interval.
- It Will have to be easily updated, i.e. adding an increase/decrease over an interval.
So my question is what is the best data structure for this sort of thing? I was thinking that due to the random access nature a Binary tree is the most likely, but I’m hoping I’m not missing something. Also is there a good implementation already out there for C++.
Yes, since the intervals cannot overlap, binary tree is the right data structure. If you did not need fast updates, it could be as simple as having a sorted sequence of the interval endpoints; querying the function value at a certain location could be done using, for example, one of the STL binary search methods
std::lower_boundorstd::upper_bound, evaluating over a range using two searches. However, for fast updates a self-balancing binary tree is naturally better.The standard library does define a container with tree-like access:
std::map(although it is not required to be implemented using a binary tree, it usually is).for completeness, it should be mentioned that Boost ICL library has an
interval_map, astd::map-like container that uses intervals as keys and with aggregate on overlap insertion semantics.