MMoRe MMoRe - 8 months ago 147
C++ Question

error: invalid user defined conversion from char to const key_type&

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?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download