user4437048
user4437048

Reputation: 15

map.find(var) isn't returning correct value

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

Answers (3)

Yetti99
Yetti99

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

VolAnd
VolAnd

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

zmbq
zmbq

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

Related Questions