A map as you implemented it is already a pretty good way to associate the few slots-with-a-value, to that value, and considering that any slot not found in the map holds a default value. (exactly as you check for, line 48).
However you’d maybe like to have both an operator const accessor, and an operator write-able accessor.
Here it seems like you’d add default values to your map even when reading the slot, which seems like defeating the purpose of the sparse map in the first place.
Now, insisting on fitting both read/write cases to same operator could be tricky, and solving this kind of concerns in the context of idiomatic c++ templates would maybe require defining things in terms of “iterators” ? Also, here the reference to the held value which is returned by the operator method will be invalidated each time the map instance reorganizes, possibly leaving nasty wrong memory address bugs depending on your use cases. I do not have the time to give it any more thoughts today, though.
[Edit] : I believe “map/unordered_map” implementation itself does not give a try at “fitting both read/write cases to same operator” : for immutable read access, you’ll use find().
So, i’d advise for another method along with operator (operator now being intended used as lhv only) :
const _Tpr& get(ConstructableArray<_Tpi,_Ndim> loc) const {
auto it=sparse_map.find(loc);
if(it==sparse_map.end()){
return default_value;
} else {
return it->second;
}
}
You then could use that structure directly for random access read/write, instead of having to convert to a full-valued vector and getting headaches about 2D typing concerns for that conversion (Unless you somehow absolutely need to send your data as a full-valued array, that is) .
“map” instead of “unordered_map” would not require a hash.