gpt4 book ai didi

c++ - unordered_map 无法检索在参数中指定为变量的键的值

转载 作者:行者123 更新时间:2023-11-28 05:06:31 24 4
gpt4 key购买 nike

我需要从 unordered_map 中提取特定值。但是,unordered_map 无法在其方括号内查找变量。

在下面的代码中cout << m[code[i]] << " ";正在抛出错误。

#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main()
{
string code;
cout << "Enter code: ";
getline(cin, code);

unordered_map<string, string> m = {
{"A","Jan"},{"B","Feb"},{"C","Mar"},{"D","Apr"},
{"E","May"},{"F","Jun"},{"G","Jul"},{"H","Aug"},
{"I","Sep"},{"J","Oct"},{"K","Nov"},{"L","Dec"}
};

for(int i=0 ; i<code.length() ; i++) {
cout << m[code[i]] << " ";
}

return 0;
}

错误信息:

main.cpp:18:18: No viable overloaded operator[] for type 'unordered_map' (aka 'unordered_map, allocator >, basic_string, allocator > >')

最佳答案

给定code与类型 string , code[i]返回 char (但不是 string );这与 map 的键类型不匹配。

您可以将 map 类型更改为 unordered_map<char, string> ,例如

unordered_map<string, string> m = {
{'A',"Jan"},{'B',"Feb"},{'C',"Mar"},{'D',"Apr"},
{'E',"May"},{'F',"Jun"},{'G',"Jul"},{'H',"Aug"},
{'I',"Sep"},{'J',"Oct"},{'K',"Nov"},{'L',"Dec"}
};

如果您想使用 unordered_map<string, string> , 你必须传递 stringunordered_map::operator[] .例如

cout << m[string(1, code[i])] << " ";

关于c++ - unordered_map 无法检索在参数中指定为变量的键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44621894/

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