c++ - Using char as array index after using map -
i trying use character index array of integers after mapping it. problem whenever try access array using variable of type char(as array[char]), instead of using array["], getting error compiler. wonder if necessary use constant types after mapping. here code.
int count=0; int length=strlen(word); std::map<std::string, int, std::less<std::string> > alpha; alpha["x"]=1; alpha["y"]=2; alpha["z"]=3; char temp; for(int i=0;i<length;i++) { temp=word[i]; count=alpha[temp]; }
error(s) :
error: invalid user-defined conversion 'char' 'std::map, int, std::less > >::key_type&& {aka std::basic_string&&}' [-fpermissive] count=alpha[temp];
error: initializing argument 1 of 'std::basic_string<_chart, _traits, _alloc>::basic_string(const _chart*, const _alloc&) [with _chart = char; _traits = std::char_traits; _alloc = std::allocator]' [-fpermissive] basic_string(const _chart* __s, const _alloc& __a = _alloc());
there's no automatic conversion char
std::string
. have 2 options:
- make conversion explicit,
count=alpha[std::string(1,temp)];
- change type of
temp
std::string
. can assignchar
string
, intuitive result, rest of code work
if all map keys single-character strings, might consider using char
key; or using flat array large enough character value might need.
Comments
Post a Comment