JavaEar 专注于收集分享传播有价值的技术资料

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?

3个回答

    最佳答案
  1. 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.

  2. 参考答案2
  3. 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 
    
  4. 参考答案3
  5. 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:

    • create a string from the word[3]
    • use substr(3,1) to get the key