**已关闭。**此问题为not reproducible or was caused by typos。当前不接受答案。
这个问题是由一个错字或一个无法再复制的问题引起的。虽然类似的问题可能是on-topic在这里,但这个问题的解决方式不太可能帮助未来的读者。
8天前关闭
Improve this question
我试图在cpp中使用unordered map将罗马数字转换为int,只是为了避免if else或switch。你可以说我试图实现我在一个问题中学到的东西。我写了这个:
#include<bits/stdc++.h>
using namespace std;
int romanToInt(string s)
{
int result=0;
unordered_map <string, int> roman;
roman["I"] = 1;
roman["V"] = 5;
roman["X"] = 10;
roman["L"] = 50;
roman["C"] = 100;
roman["D"] = 500;
roman["M"] = 1000;
for( int i=0; i < s.length(); i++ )
{
result += roman[s[i]];
}
return result;
}
int main(){
cout << romanToInt("XIII");
}
它不起作用,我没有得到什么错误。我尝试了cout〈〈roman[“X”],它给出了输出10,但当我传递s[i]甚至s[1]作为roman的参数时,它不起作用。请帮助,因为我不理解编译器的错误消息,也不知道如何解决它。
编译器的错误:
983 | operator[](key_type&& __k)
| ^~~~~~~~
d:\appdata\mingw\include\c++\11.2.0\bits\unordered_map.h:983:29: note: no known conversion for argument 1 from '__gnu_cxx::__alloc_traits<std::allocator<char>, char>::value_type' {aka 'char'} to 'std::unordered_map<std::__cxx11::basic_string<char>, int>::key_type&&' {aka 'std::__cxx11::basic_string<char>&&'}
983 | operator[](key_type&& __k)
| ~~~~~~~~~~~^~~
1条答案
按热度按时间x8diyxa71#
索引
std::string
的结果是char
。您的map
的键是std::string
。当您尝试执行roman[s[i]];
时,它会尝试在std::string
键Map中查找char
,这不起作用(没有为char
定义隐式转换为std::string
)。最简单的修复方法是将map
更改为char
键:您还可以通过直接构造
unordered_map
来缩短和优化代码,并使其成为static
,这样就不会在每次调用时都重新构建它,只需将上面的所有代码替换为: