【问题标题】:error: invalid user defined conversion from char to const key_type&错误:从 char 到 const key_type& 的用户定义转换无效
【发布时间】:2017-10-02 22:23:47
【问题描述】:

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

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

例子:

#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;
}

我做错了什么?

【问题讨论】:

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

标签: c++ string c++11 dictionary compiler-errors


【解决方案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;
}

正如其他人所观察到的,现在您正尝试使用char 作为std::map 的键,其中键是std::string。并且没有从charstd::string 的自动转换。

小题外话建议:避免为变量提供与类型相同的名称,例如您命名为 mapstd::map。这是合法的,但容易混淆。

【讨论】:

    【解决方案2】:

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

    只需取字符串的子字符串(通过使用string::substr),通过改变这个:

    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 
    

    【讨论】:

      【解决方案3】:

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

      • 从单词[3]创建一个字符串
      • 使用 substr(3,1) 获取密钥

      【讨论】:

        猜你喜欢
        • 2023-03-26
        • 2018-03-24
        • 1970-01-01
        • 1970-01-01
        • 2022-11-13
        • 2021-01-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多