Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Address of map value

Tags:

c++

pointers

map

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?

like image 862
Max Frai Avatar asked Nov 22 '11 21:11

Max Frai


People also ask

Is map a pointer in Golang?

Maps, like channels, but unlike slices, are just pointers to runtime types. As you saw above, a map is just a pointer to a runtime. hmap structure. Maps have the same pointer semantics as any other pointer value in a Go program.


1 Answers

Best use a reference:

int & time = mSettings["WorldTime"];

If the key doesn't already exist, the []-access will create the element (and value-initialize the mapped value, i.e. 0 for an int). Alternatively (if the key already exists):

int & time = *mSettings.find("WorldTime");

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.

like image 152
Kerrek SB Avatar answered Oct 21 '22 01:10

Kerrek SB