c++ 使用无序Map将罗马数字转换为cpp中的整数[已关闭]

lokaqttq  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(212)

**已关闭。**此问题为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)
      |                  ~~~~~~~~~~~^~~
x8diyxa7

x8diyxa71#

索引std::string的结果是char。您的map的键是std::string。当您尝试执行roman[s[i]];时,它会尝试在std::string键Map中查找char,这不起作用(没有为char定义隐式转换为std::string)。最简单的修复方法是将map更改为char键:

unordered_map<char, int> roman;  // Change string to chat
roman['I'] = 1;   // Change double-quotes to single-quotes so you're using char
roman['V'] = 5;   // Do it for all of them
// ...
roman['M'] = 1000;

您还可以通过直接构造unordered_map来缩短和优化代码,并使其成为static,这样就不会在每次调用时都重新构建它,只需将上面的所有代码替换为:

static unordered_map<char, int> roman{{'I',1},{'V',5},{'X',10},{'L',50},{'C',100},{'D',500},{'M',1000}};

相关问题