为什么我的 RLE 代码显示 std out of range for c++?

Why does my RLE code show std out of range for c++?

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

terminate called after throwing an instance of '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())

相反。