C++ 意外数组溢出

C++ Unexpected Array Overflow

大约 50 分钟前,我开始从事一个项目,我将一个带有罗马数字的字符串转换为一个整数。我遇到了一个“数组溢出”的问题,我已经进行了 30 分钟的故障排除,但由于找不到解决方案而感到有点沮丧。显示的错误如下

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::at: __n (which is 3) >= this->size() (which is 3)

这是我的代码:

class Solution {
  public:
    int romanToInt(string s) {
      int result = 0;
      char letters[7] = {'M','D','C','L','X','V','I'};
      int numbers[7] = {1000,500,100,50,10,5,1};
      for(int i=0; i<s.length(); i++) {
        if(i!=(s.length()-1)) {
          char *foo = std::find(std::begin(letters), std::end(letters), s.at(i));
          char *nfoo = std::find(std::begin(letters), std::end(letters), s.at(i+1));
          int num = numbers[std::distance(letters, foo)];
          int num2 = numbers[std::distance(letters, nfoo)];
          if(num<num2) {
            result+=(num2-num);
          }
          else {
            result+=num2;
          }
        }
        else {
          char *foo = std::find(std::begin(letters), std::end(letters), s.at(i));
          int num = numbers[std::distance(letters, foo)];
          result+=num;
        }
      }
      return result;
    }
};

您的代码可以稍微清理一下:

int Roman_To_Decimal(const std::string& roman_number)
{
    static const char roman_letters[] = {'M','D','C','L','X','V','I'};
    static const int  values[] = {1000, 500, 100, 50, 10, 5, 1};
    const unsigned int string_length = roman_number.length();
    int decimal_value = 0;
    char const * const end_letter_iterator = &roman_letters[sizeof(roman_letters)];
    char const * const begin_letter_iterator = &roman_letters[0];
    for (unsigned int i = 0; i < string_length; ++i)
    {
       const char roman_digit = roman_number[i];
       char * position = std::find(begin_letter_iterator,
                                   end_letter_iterator,
                                   roman_digit);
       if (position != end_letter_iterator)
       {
           unsigned int index = position - begin_letter_iterator;
           const int digit_value = values[index];
           decimal_value += digit_value;
       }
    }
    return decimal_value;
}

上面的代码不处理较小的罗马数字(字母)在较大的罗马数字(字母)之前的情况,例如 IX (9) 和 IV (4) 的情况。这是 OP 或 reader.

的练习

此外,上述函数是独立的,即在 class 之外,因为在 C++ 中并非所有内容都必须在 class 中。