unordered_map 无法检索在参数中指定为变量的键的值
unordered_map is unable to retrieve value for a key specified as a variable in argument
我需要从 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]
returns 一个 char
(但不是 string
);这与地图的键类型不匹配。
您可以将地图类型更改为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>
,您必须将 string
传递给 unordered_map::operator[]
。例如
cout << m[string(1, code[i])] << " ";
我需要从 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]
returns 一个 char
(但不是 string
);这与地图的键类型不匹配。
您可以将地图类型更改为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>
,您必须将 string
传递给 unordered_map::operator[]
。例如
cout << m[string(1, code[i])] << " ";