Why does my map inside Test does not return its value? What’s wrong with this?
class Test{ //Test.h
public:
std::map< char*, int> mm;
Test();
void set();
int get( char*);
};
Test::Test(){ //Test.cpp
}
void Test::set(){
mm["aaa"] = 24;
}
int Test::get( char* n){
return mm[n];
}
int main(){ //main.cpp
Test *test = new Test();
test->set();
//this returns 0 instead of 24
printf("From Test: %d\n", test->get("aaa"));
printf("From Test: %d\n", test->mm["aaa"]);
delete test;
//this map works
std::map<char*, int> mm;
mm["a"] = 54;
printf("Local: %d\n", mm["a"]);
return 0;
}
Needs extra text to post >.<
Oops! Your question couldn’t be submitted because:
Your post does not have much context to explain the code sections; please explain your scenario more clearly.
It fails because you use char* pointer as a key. For two literals addresses will be different. To make map work properly you must use some other string class which has operator< defined. std::string, for instance.