So I want an interface that stores some numbers in order and efficiently perform some operations on them. In practise, a sorted vector performs very well for small sizes, but for theoretical performance and performance on larger instances, I need also a variant that uses something like std::set
to perform inserts and erases in O(log n)
time.
Here some implementation for the vector variation:
#include <vector>
#include <algorithm>
class Numbers {
public:
template<class ForwardIt>
void unguarded_insert(ForwardIt it, int val) { vec.insert(it, val); }
auto lower(int val) { return std::lower_bound(vec.begin(), vec.end(), val); }
template<class ForwardIt>
void unguarded_replace(ForwardIt it, int val) { *it = val; }
template<class ForwardIt>
auto erase_elements(ForwardIt first, ForwardIt last) { return vec.erase(first, last); }
private:
std::vector<int> vec;
};
Note that for insertion and replacing it it ensured by the caller that they are at the right position. For example the caller might want to delete all elements between 20 and 50 and insert 30. So one can call lower_bound
, replace the first element and delete the remaining range.
I do not want to write the entire interface twice and would like a templated solution using the container type as template argument. However, I am running into problems like lower_bound
is a member function for some containers and a free function for other containers. Also insertion and replacing at an iterator cannot really be done by std::set
because the order is unnecessarily checked (right?).
So is there some way to fix these problems or a different kind of approach that solves my problem? The solution should not do unnecessary work on either container just to make it work on both.