I'm trying to create a "sparse" vector class in C++, like so:
template<typename V, V Default>
class SparseVector {
...
}
Internally, it will be represented by an std::map<int, V>
(where V
is the type of value stored). If an element is not present in the map, we will pretend that it is equal to the value Default
from the template argument.
However, I'm having trouble overloading the subscript operator, []
. I must overload the []
operator, because I'm passing objects from this class into a Boost function that expects []
to work correctly.
The const
version is simple enough: check whether the index is in the map, return its value if so, or Default
otherwise.
However, the non-const version requires me to return a reference, and that's where I run into trouble. If the value is only being read, I do not need (nor want) to add anything to the map; but if it's being written, I possibly need to put a new entry into the map. The problem is that the overloaded []
does not know whether a value is being read or written. It merely returns a reference.
Is there any way to solve this problem? Or perhaps to work around it?