【问题标题】:Why does my RLE code show std out of range for c++?为什么我的 RLE 代码显示标准超出 C++ 范围?
【发布时间】:2019-09-30 22:53:13
【问题描述】:

每当我尝试运行此程序时,它总是向我显示错误消息

在抛出 'std::out_of_range' 的实例后调用终止

我发现,当我尝试将输入作为字符串时,就会发生这个问题。因此,我的循环无法正确执行。

如果有人能解释我的代码有什么问题,我真的很感激!

#include <iostream>
#include <vector>
#include <stdexcept>
#include <string>
using namespace std;

int main()
{
    vector<string> compressed_run_lengths_data;
    vector<char> compressed_characters_data;
    int i;
    int count = 1;
    bool can_be_compressed = false;
    string data;

    try
    {
        cout << "Enter the data to be compressed: ";
        getline(cin, data);

        for (i = 0; i < data.size(); ++i)
        {
            if (!isalpha(data.at(i)))
            {
                throw runtime_error("error: invalid input");
            }
        }

        if (!data.empty())
        {
            i = 1;

            while (i <= data.size())
            {
                if (data.at(i - 1) == data.at(i))
                {
                    count++;

                    if (count > 1)
                    {
                        can_be_compressed = true;
                    }
                }
                else
                {
                    compressed_characters_data.push_back(data.at(i - 1));
                    compressed_run_lengths_data.push_back(to_string(count));
                    count = 1;
                }

                ++i;
            }

            if (can_be_compressed)
            {
                for (i = 0; i < compressed_run_lengths_data.size(); ++i)
                {
                   cout << compressed_run_lengths_data.at(i) << compressed_characters_data.at(i);
                }
            }
            else
            {
               data;
            }         
        }
    }
    catch (runtime_error &e)
    {
        cout << e.what();
        return 1;
    }

    return 0;
}

【问题讨论】:

  • 你有while (i &lt;= data.size()),然后调用data.at(i),这是数组末尾的一个。
  • 但这就是我们运行循环来访问向量元素的方式,对吧?当 i = 1 时,data.at(1-1) 会给我索引 0 处的元素。
  • 请重新阅读我的评论。它应该告诉你你需要知道的一切。
  • 您能详细说明一下吗?对不起,我不明白为什么while循环里面的表达式是错误的

标签: c++ c++11 run-length-encoding


【解决方案1】:

根据要求,对我的 cmets 进行详细说明:

while (i <= data.size())                // <- i runs up to and including data.size ()
{
    if (data.at(i - 1) == data.at(i))   // data.at (i) is out of range when i == data.size ()

我没有分析你的算法,但你可能想要:

while (i < data.size())

改为。

【讨论】:

  • 就此而言,一旦循环正确地保持在data 的范围内,您应该将at() 替换为operator[],因为您不再需要额外的边界检查。
猜你喜欢
  • 2015-09-10
  • 2016-03-07
  • 2016-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-20
  • 1970-01-01
相关资源
最近更新 更多