Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to prevent insert or erase on STL unordered_map?

I frequently use unordered_maps with fixed / constant keys, but mutable values. Example: If you have an enum Dimension{ X, Y }, you might want to store a data point for each but never allow inserts or deletes for the map. Updates are OK.

Example initialisation:

typedef std::unordered_map<Dimension, std::size_t> Dimension_To_Size_Map;
// assume std::hash has template specialisation for enum
Dimension_To_Size_Map dimension_To_Size_Map =
    { { Dimension.X, 0 }, { Dimension.Y, 0 } };
dimension_To_Size_Map[Dimension.X] = 12;  // update is ok
dimension_To_Size_Map[Dimension.Y] = 17;  // update is ok
dimension_To_Size_Map[(Dimension)7] = 22;  // insert not allowed
dimension_To_Size_Map.erase(Dimension.X);  // erase not allowed

It is possible to prevent insert or erase, but allow update, on STL unordered_map?

One idea: Copy, rename, and modify an existing implementation of unordered_map to remove insert and erase.

like image 361
kevinarpe Avatar asked Mar 16 '23 02:03

kevinarpe


1 Answers

You could derive your own map class from std::map via private inheritance and expose only the functions of std::map that you want to provide access to.

like image 78
Tamás Szabó Avatar answered Mar 18 '23 14:03

Tamás Szabó