2

I'm trying to use a string as key for an std::map because that string can be changed from different parts of the program but I get a problem that I can store data in the map easily but I can't access it because it is asking for the pointer address as the key and I want to access that data from the string's value.

Here is the code

using namespace std;

string *AString = "pointer";

map<string *, bool> AMap; //Declare
AMap[AString] = true; //Insert into map with key AString

cerr << AMap["pointer"]; //Does not work
1
  • 3
    You can't change the key of a entry inside a std::map. I guess you have to rethink why you wan't to do this. You could store a string as key, and everytime the key is changed you erase the old entry and reinsert it to the map with the updated key. Commented Dec 27, 2011 at 18:50

3 Answers 3

3

The solution is to not use a pointer:

using namespace std;

string AString = "pointer";

map<string, bool> AMap;
AMap[AString] = true;

cerr << AMap["pointer"];

You really do not want a map key to be changed from other parts of the program while it's in the map. This just asks for trouble and indicates a design problem.

Sign up to request clarification or add additional context in comments.

1 Comment

Why can't we use shared variable as a key in a map? I want to use a pointer because the value changes and I want the key to stay the same if it changes.
2

Looks like you may be coming from Java or C#?

std::string aString = "Not a Pointer";
std::map<std::string, bool> aMap;
aMap[aString] = true;
std::cerr << aMap["pointer"];

You should not be using pointers to strings in this case. Just use a map of strings instead of your map of string pointers.

In this case, std::cerr << aMap["pointer"]; works because the "pointer" gets converted into a std::string and is then looked up in the map by the string value.

Comments

2

"pointer" is a C string that the AString pointer points to in memory. You need to do:

cerr << AMap[AString];

You could also use a a std::map<std::string,bool> which is less error prone and what you probably mean to do. Do you really want to use a pointer for a key? Creating another pointer pointing to a string with value "pointer" would not be the same key for instance.

std::string *BString(new std::string("pointer")); 
AMap[BString] = true; //Not the same key

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.