I have a settings which are stored in std::map. For example, there is WorldTime key with value which updates each main cycle iteration. I don’t want to read it from map when I do need (it’s also processed each frame), I think it’s not fast at all. So, can I get pointer to the map’s value and access it? The code is:
std::map<std::string, int> mSettings;
// Somewhere in cycle:
mSettings["WorldTime"] += 10; // ms
// Somewhere in another place, also called in cycle
DrawText(mSettings["WorldTime"]); // Is slow to call each frame
So the idea is something like:
int *time = &mSettings["WorldTime"];
// In cycle:
DrawText(&time);
How wrong is it? Should I do something like that?
Best use a reference:
If the key doesn’t already exist, the
[]-access will create the element (and value-initialize the mapped value, i.e.0for anint). Alternatively (if the key already exists):As an aside: if you have hundreds of thousands of string keys or use lookup by string key a lot, you might find that an
std::unordered_map<std::string, int>gives better results (but always profile before deciding). The two maps have virtually identical interfaces for your purpose.