gpt4 book ai didi

c++ - 错误 : invalid user defined conversion from char to const key_type&

转载 作者:行者123 更新时间:2023-11-30 03:28:31 25 4
gpt4 key购买 nike

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

F:\Programming\korki\BRUDNOPIS\main.cpp|14|error: invalid user-defined conversion from 'char' to '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;
}

我做错了什么?

最佳答案

I am trying to assign int type value to each letter in latin alphabet using std::map.

所以你必须使用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: :字符串。并且没有从 charstd::string 的自动转换。

一点题外话的建议:避免给一个类型同名的变量,比如你命名为 mapstd::map。这是合法的,但容易混淆。

关于c++ - 错误 : invalid user defined conversion from char to const key_type&,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46534587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com