调试时矢量下标超出范围

vector subscript out of range when debugging

本文关键字:范围 下标 调试      更新时间:2023-10-16

代码是构建最小堆的一部分。看来下面这句话出错了。

if ((child < (int)heap.size() - 1) && (heap[leftchild].cost > heap[leftchild + 1].cost))

但是我不知道如何管理它。有人提供帮助吗?谢谢!!

void heap_adjust_down(vector<rt_node> & rt, vector<h_node> & heap)
{
    cout << "the" << heap.size() << "times" << endl;
    cout << heap[heap.size()-1].id << endl;
    int child;
    for (int i = heap.size() / 2; i >= 0; i--)
    {
        cout << " into build heap, i = " << i << endl;
        int leftchild = 2 * i + 1;
        h_node temp_h;
        for (temp_h = heap[i]; leftchild < (int)heap.size(); i = child)
        {
            leftchild = 2 * i + 1;
            cout << "  into percdown" << endl;
            child = leftchild;
            if ((child < (int)heap.size() - 1) && (heap[leftchild].cost > heap[leftchild + 1].cost))
            {
                child++;
            }
            if (heap[child].cost < temp_h.cost )
            {
                heap[i] = heap[child];
                rt[i].h_pos = child;
            }
            else break;
            cout << "i = " << i << endl;
        }
        heap[i] = temp_h;
        rt[i].h_pos = i;
    }
}

问题更可能是这一行:

if (heap[child].cost < temp_h.cost )

此行没有像您在上一个 if 语句中类似所做的那样检查child < size。此外,在内部 for 循环的第二次迭代中,leftchild至少会加倍(子项也是如此)。这似乎不是你的意图。(leftchild将加倍,因为您在循环迭代器中设置i = child

内部的 for 循环需要重新考虑。例如,您的测试表达式测试该leftchild < size,但随后您立即根据i重新计算leftchild,有点使该测试无效。