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


  抛出'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 <= 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())


代替。

关于c++ - 为什么我的RLE代码在c++中显示std超出范围?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58176189/

10-13 08:15
查看更多