Soulslayer
Soulslayer

Reputation: 118

map::find() cannot find an existing key

I'm just trying to use the standard std::map, and I'm having troubles. I remembered to include the headers, and here is my declaration:

std::map<const char *, UINT> boneList;

I've filled it in with some data, but when I try to find a value like this:

std::cout << boneList.find("Bind_Spine1")->second;

But instead of printing a number, an error pops during runtime: "map/set iterator not derefernciable".

But if I do this:

std::cout << boneList["Bind_Spine1"];

Everything works just fine. Why the find() is returning end() when operator[] is not? I am using visual studio 13

Upvotes: 0

Views: 1971

Answers (1)

R Sahu
R Sahu

Reputation: 206737

boneList["Bind_Spine1"] will add an item to the map if doesn't exist. boneList.find("Bind_Spine1") will not do that.

Change the key in the map to std::string. That should fix the problem. When you use char const* as the key of the map, it will all seem confusing. In C/C++, if you have

char const* ap = "abcd"; 
char const* bp = "abcd";

Then it's not guaranteed that a == b. However if you use

std::string a = "abcd"; 
std::string b = "abcd";

Then it is guaranteed that a == b.

Upvotes: 2

Related Questions