c++ - QVector<T>::operator[] 失败:意外抛出 "index out of range"

标签 c++ qt sorting vector indexoutofrangeexception

我有两种排序方法:插入排序和shell排序。其中两个工作函数我已经从纯 C 适应了 C++。问题是 ins_sort 函数工作得很好,而 shell_sort 失败了。这可能是什么原因?

    bool less(QVector<int> &arr, int a, int b)
    {
        return arr[a] < arr[b];
    }

    // Performs swap on elements at a and b in QVector<int> arr
    void qswap(QVector<int> &arr, int a, int b)
    {
        int temp = arr[a];
        arr[a] = arr[b];
        arr[b] = temp;
    }

    /* Failure is thrown in this method */
    void shell_sort(GraphicsView &window, SwapManager &manager)
    {
        auto list = window.items();
        QVector<int> arr;
        for (auto item : list)
            arr.push_back(static_cast<QGraphicsRectWidget*>(item)->m_number);
        int N = arr.size();
        int h = 1;
        while (h < N/3) h = 3*h  + 1;
        while (h >= 1)
        {
            for (int i = h; i < N; ++i)
            {
                for (int j = i; less(arr, j, j-h) && j >= h; j -= h)
                {
                    qswap(arr, j, j-h);
                    manager.addPair(j, j - h);
                }
            }
            h /= 3;
        }
    }

那个做得很好。

    /* This method works just fine */
    void ins_sort(GraphicsView &window, SwapManager &manager)
    {
        auto list = window.items();
        int i, j;
        QVector<int> arr;

        for (auto item : list)
        {
            arr.push_back(static_cast<QGraphicsRectWidget*>(item)->m_number);
        }
        int N = arr.size();
        for (i = 1; i < N; ++i)
        {
            for (j = i - 1; j != -1 && less(arr, j + 1, j); --j)
            {
                qswap(arr, j, j + 1);
                manager.addPair(j, j + 1);
            }
        }
    }

调试器指向“qvector.h”中的这段代码

    Q_ASSERT_X(i >= 0 && i < d->size, "QVector<T>::operator[]", "index out of range");
      return data()[i]; }

最佳答案

在 for 循环条件中,比较项目之前检查 j 值是有意义的:

for (int j = i; j >= h && less(arr, j, j-h); j -= h)

关于c++ - QVector<T>::operator[] 失败:意外抛出 "index out of range",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41012769/

相关文章:

java - 按列表值对 Java Map 进行排序

c++ - WinSock c++ inet_ntop 总是显示 204.204.204.204(并且 accept() 没有失败)

c++ - 使用 Matio 在 C++ 中打开 3d matlab 文件

c++ - 使用 Qt 套接字广播大数据

c++ - Qt Creator 中对 glu 的 undefined reference

Pythonic 按字段名称对命名元组列表进行排序的方法

linux - svn 状态 | sort - 不对输出进行排序

c++ - Qt 图形用户界面 : misaligned things in groupBox with horizontal Layout

C++ 11 正则表达式堆栈溢出/VS2012

java - Swing - Qt 信号/槽的替代品