Reputation: 29
I am trying to assign int
type value to each letter in latin alphabet using std::map
. When I want to create new int and give it a value equal to int
mapped to word, i get an error:
F:\Programming\korki\BRUDNOPIS\main.cpp|14|error: invalid user-defined conversion from 'char' to 'const key_type& {aka const std::basic_string&}' [-fpermissive]|
Example:
#include <iostream>
#include <string>
#include <cstdlib>
#include <map>
using namespace std;
int main()
{
std::map <std::string,int> map;
map["A"] = 1;
int x;
std:: string word = "AAAAAA";
x = map[word[3]];
cout << x;
return 0;
}
What am I doing wrong?
Upvotes: 2
Views: 3613
Reputation: 66230
I am trying to assign int type value to each letter in latin alphabet using std::map.
So you have to use char
(instead of std::string
) as key of the map; something like
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<char, int> map;
map['A'] = 1;
int x;
std:: string word = "AAAAAA";
x = map[word[3]];
std::cout << x << std::endl;
return 0;
}
As observed by others, now you're trying to use a char
as a key for a std::map
where the key is a std::string
. And there isn't an automatic conversion from char
to std::string
.
Little Off Topic suggestion: avoid to give a variable the same name of a type, like your std::map
that you've named map
. It's legit but confusion prone.
Upvotes: 2
Reputation: 73444
word[3]
is of type char
, and your map has a key of type std::string
. There is no conversion from char
to std::string
.
Just take the substring of the string (by using string::substr
), by changing this:
x = map[word[3]];
to this:
x = map[word.substr(3, 1)];
Or better yet, use char
as your key, since you need letters, like this:
std::map <char, int> map;
map['A'] = 1;
// rest of the code as in your question
Upvotes: 1
Reputation: 9643
word[3]
is a character at the fourth position of the string. But you can't use that as a key for the map because the map uses a string as it's key. If you change the map to have a key of char then it will work or you can:
Upvotes: 0