C++ 错误:从char到const key类型的用户定义转换无效&;

C++ 错误:从char到const key类型的用户定义转换无效&;,c++,string,c++11,dictionary,compiler-errors,C++,String,C++11,Dictionary,Compiler Errors,我正在尝试使用std::map为拉丁字母表中的每个字母分配int类型值。当我想创建新的int并给它一个等于映射到word的int的值时,我得到一个错误: F:\Programming\korki\BRUDNOPIS\main.cpp | 14 |错误:用户定义的从“char”到“const key_type&{aka const std::basic_string&}”的转换无效[-fppermissive]| 例如: #include <iostream> #include <

我正在尝试使用
std::map
为拉丁字母表中的每个字母分配
int
类型值。当我想创建新的int并给它一个等于映射到word的
int
的值时,我得到一个错误:

F:\Programming\korki\BRUDNOPIS\main.cpp | 14 |错误:用户定义的从“char”到“const key_type&{aka const std::basic_string&}”的转换无效[-fppermissive]|

例如:

#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;
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
地图;
地图[“A”]=1;
int x;
std::string word=“AAAAAA”;
x=地图[word[3]];

cout
word[3]
的类型为
char
,并且您的地图的键类型为
std::string
。没有从
char
std::string
的转换

通过更改以下内容,只需获取字符串的子字符串(通过使用):

x = map[word[3]];
为此:

x = map[word.substr(3, 1)];

或者更好地使用
char
作为键,因为您需要字母,如下所示:

std::map <char, int> map;
map['A'] = 1;
// rest of the code as in your question 
std::map;
map['A']=1;
//其余代码与您的问题相同

word[3]
是字符串第四个位置的字符。但您不能将其用作映射的键,因为映射使用字符串作为键。如果您将映射更改为具有char键,则它将起作用,或者您可以:

  • 从单词[3]创建一个字符串
  • 使用substr(3,1)获取密钥
我正在尝试使用std::map为拉丁字母表中的每个字母分配int类型值

因此,您必须使用
char
(而不是
std::string
)作为映射的键;类似

#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;
}
#包括
#包括
#包括
int main()
{
地图;
map['A']=1;
int x;
std::string word=“AAAAAA”;
x=地图[word[3]];

std::cout@juanchopanza-你是对的;但是…我的回答太琐碎了…删除了。