Reputation: 15
Sample code is :
map<char* , int> map;
map["Privilege"] = 1;
char* code[]="Privilege";
val = map.find(code); // returns map.end()
val = map.find("Privilege"); // returns correct value
I need to find the value in the map on the basis of variable key :
val = map.find(code);
It is returning
map.end()
Please suggest something
Upvotes: 1
Views: 278
Reputation: 328
Use std::string instead of char * Since you want to save the string value, not its location. Also, I wouldn't use the name "map" for a variable (since its already used)
#include <map>
#include <string>
std::map<std::string, int> mymap;
mymap["Privilege"] = 1;
std::string code = "Privilege";
val = mymap.find(code);
val = mymap.find("Privilege");
Upvotes: 1
Reputation: 6407
In C++ application do not use char*
, use string
instead. I mean, define map as map<string , int> MyMap;
By the way, map
is not good name for variable :-)
Upvotes: 1
Reputation: 39013
You're storing character pointers in your map, not strings. map.find
compared the two pointers and finds them not equal.
Just use a map<string, int>
.
Upvotes: 0