Sign in to follow this  
TFS_Waldo

Mapping strings to variables?

Recommended Posts

Hey, everyone. I'm back. I have used 'std::map' to map strings to function pointers. But now, I need to know if I can map strings to variables. I have tried it, but it is not what I need. I tried it the way I did strings to func. ptrs. I need to change an actual 'int nInt;' when I 'insert' into the map: ex.: int nVar1 = 0; myMap.insert("str", nVar1); How do I change the value of 'nVar1' in the map? I know you can use 'theMap->second' to get the value, but it is a 'const', so I can't change it. Thanks in advance! =)

Share this post


Link to post
Share on other sites
You can make the map store a (smart) pointer to the variable you want to alter. Just be careful that the variable doesn't go out of scope, get deleted, etc.

Share this post


Link to post
Share on other sites
Why is it a const? Only the key in a map should be const, not the value. They should function much like an array, except with arbitrary key values rather than numerical key values. Are you using a const_iterator by mistake? (Or have I totally forgotten something, having not used C++ for months?)

Share this post


Link to post
Share on other sites
std::map<std::string, int> vars;

vars["foo"] = 25;
vars["foo"] += 2;
std::cout << vars["foo"] << std::endl;

Share this post


Link to post
Share on other sites
Well it really depends on where the variable is declared and how it is used. Typically you will simply map functions which allow you to retrieve or change the value of the variable. This is usually desirable rather than granting direct access to the variable. One problem you are bound to run into is directly mapping structure/class members for direct access. Sometimes it's more desirable to map the vars for direct access (especially for the countless windows API structs) but becomes tricky. In these cases you need to calculate and store the offset rather than a pointer to the data type. You can do this with a macro similar to the following:

#define get_var_offset(type, var)	((int)&(((type*)0)->var))


This returns a zero based offset into the structure for where the variable resides. If you're not using structures simply map the pointer to the variable.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this