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

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

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

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())

相反。

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

相关文章:

c++ - 将 3D 数组( vector )转换为 vtk 非结构化网格

c++ - 指向 shared_ptr 成员变量的指针

c - 使用 C 对 bmp 文件进行游程编码时的平台相关问题

c++ - 如何在 Qt DBus 调用中从 QDBusMessage 中提取返回的数据?

c++ - 使用 libcurl 和 SSL

C++ 元组链接问题 : undefined reference

c++ - 对象的 Range Base 循环

haskell - 组合学:圣彼得博弈算法

python - 在 Python 中将 5A2B4C11G 字符串转换为 [(5 ,"A"),(2 ,"B"),(4 ,"C"),(11 ,"G")]

c++ - 我可以使用 boost 池作为存储来支持 boost 侵入式收集吗?