You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++队列空队列调用display输出0而非-1的原因排查与解决

问题原因

你的代码输出0的核心原因有两个:

  • display函数未做空队列判断就直接遍历:两次出队操作后front和rear都被重置为-1,此时循环条件i = front; i <= rear等价于i=-1; i<=-1,循环会执行一次,访问数组下标-1的内存,这属于越界访问的未定义行为,你当前运行环境下该地址存储的值刚好是0,所以输出0。
  • 额外的逻辑漏洞:enque函数判断队列已满后仅打印提示,没有终止后续逻辑,就算队列满了仍会执行rear++和写入元素操作,会引发数组越界问题。
修复方案
  1. 修改display函数,先判断队列是否为空,为空时直接输出-1,否则再遍历输出队列元素:
void Q::display()
{
    if (is_empty()) {
        cout << -1 << endl;
        return;
    }
    for (int i = front; i <= rear; i++)
    {
        cout << item[i] << "	";
    }
    cout << endl;
}
  1. 修复enque函数的边界逻辑,队列满时打印提示后直接返回,不执行后续入队操作:
void Q::enque(int num)
{
    if (is_full()) {
        cout << "Sorry Enque Is Full !!" << endl;
        return;
    }
    if (front == -1)
        front = 0;
    rear++;
    item[rear] = num;
}
  1. 可选优化:优化is_empty判断逻辑,覆盖front > rear的边界场景,避免极端场景下的判断错误:
bool Q::is_empty()
{
    return front == -1 || front > rear;
}

内容的提问来源于stack exchange,提问作者golden_1A

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 08:06:03