mardi 4 avril 2023

convert a roman number to int in cpp using unordered map

I was trying to convert a roman number to int in cpp using unordered map just to avoid if else or switch. You can say I was trying to implement what I leant in a question. I wrote this:

#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");
}

it doesn't work and I dont get whats wrong. I tried 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.

The compiler's error:

  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)
      |                  ~~~~~~~~~~~^~~

Aucun commentaire:

Enregistrer un commentaire