Saif Ur Rehman
Saif Ur Rehman

Reputation: 348

Accessing a std::map with pointer type as key

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

Upvotes: 2

Views: 3943

Answers (3)

Joel
Joel

Reputation: 2966

"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

Upvotes: 2

crashmstr
crashmstr

Reputation: 28563

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.

Upvotes: 2

ChrisWue
ChrisWue

Reputation: 19020

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.

Upvotes: 3

Related Questions