C++ map problem
I have a
map<char*, int> labels;
thats exhibiting some behavior that I can't wrap my head around at all. For one index it's returning different values for what I'm pretty sure are the same indexes. Heres an example:
earlier in my program, I add an entry as follows:
labels[current->u.bj.target->name] = blockNum + 1;
//Test code
if (blockNum + 1 == 9)
{
stringtest = current->u.bj.target->name;
cout << "Condition Met" << endl;
testCond = true;
}
later on in my program, I do the following
if ((*stringtest) == (*开发者_如何学Gocurrent->u.bj.target->name))
cout << "Why is this printing the correct val " <<labels[stringtest] << endl;
branchTarget = labels[current->u.bj.target->name];
cout << "Why is this value different" << branchTarget << endl;
as you can tell from the cout statements, labels[stringtest]
returns 9, but labels[current->u.bj.target->name]
returns 0 despite the fact they both point to the same thing. Can anyone give me an idea whats wrong/how to fix it? I'm almost positive I never put 0 into the map at all.
The problem will probably disappear if you replace map<char*, int>
with map<string, int>
. That's because comparing two char*
objects will only compare the pointers, not the characters, whereas comparing two string
objects will compare the characters.
(Don't forget to #include <string>
).
It seems that current->u.bj.target->name
is a char*
. So when you write
if ((*stringtest) == (*current->u.bj.target->name))
you're dereferencing two char*
s and comparing the char
s they point to. So you're only comparing the first characters of both strings!
Also, using pointers as keys to a map
is dangerous if you're not careful. Lookups will only work correctly if you pass a pointer to the same string, not to another string that happens to contain the same characters. Use std::string
, like FredOverflow already suggested, if you want the latter behaviour.
This statement
((*stringtest) == (*current->u.bj.target->name))
compares the first character of the characters contained in the respective arrays. So there's nothing wrong with the map, you're just comparing "apples to oranges". I recommend to replace std::map< char*, int >
with std::map< std::string, int >
.
Any type of pointer will be compared (by default) by memory address, so the only way they it will return a match is if the pointers are to the same object. As other people have said, a good way round this is to use a container with a comparison operator (like std::string), or you could overload the compare function which is the third template parameter to a std::map to a class you wrote that dereferences the pointers and compares the values instead
精彩评论