使用无序映射在 cpp 中将罗马数字转换为 int

问题描述 投票:0回答:1

我试图在 cpp 中使用无序映射将罗马数字转换为 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"] and it gives the output 10 but when i pass s[i] or even s[1] as roman's argument it doesn't work. Please help as I dont understand the compiler's error message and have no idea how to solve it in my own.

编译器的错误:

  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)
      |                  ~~~~~~~~~~~^~~
c++ unordered-map
1个回答
0
投票

索引一个

std::string
的结果是
char
。您的
map
std::string
键入。当您尝试执行
roman[s[i]];
时,它会尝试在
char
键映射中查找
std::string
,这是行不通的(没有为
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}};
© www.soinside.com 2019 - 2024. All rights reserved.