C++自定义Queue类enqueue方法异常 合并有序队列出现乱值
问题排查及修复
你遇到的异常值问题全部来自main函数的录入逻辑错误,Queue类的基础入队出队功能本身没有问题,具体错误点和修复方案如下:
核心错误点
- 两个队列的录入循环中,索引变量
i定义在循环体内部,每次循环都会被重置为0,导致所有输入值只会覆盖写入数组的同一个位置,其余位置均为未初始化的垃圾值,也就是你输出看到的异常值。 - 第一个队列的录入逻辑中,
i先自增再赋值给数组,导致a[0]永远没有被赋值,自带初始垃圾值。 - 你目前的Queue类存在潜在隐患:未实现复制构造函数、私有方法
copyQueue,operator=重载调用了不存在的copyQueue函数,后续用到队列复制操作时会触发编译错误;空队列调用front()返回固定int值1,模板泛型场景下会报错;dequeue函数空队列分支无返回值,存在未定义行为。
修复后的main函数代码
int main() { Queue<int> qOne; Queue<int> qThree; cout<<"Please enter the first queue of numbers in a growing order(press a zero if you want to stop): "<<endl; int a[siz]; int i = 0; // 把索引变量移到循环外定义 while(1){ // 原siz是常量永远为真,直接写1更清晰 int n = 0; cin>>n; if(n <= 0) { cout<<"Ending the queue one's entry"<<endl; break; } qOne.enqueue(n); a[i] = n; // 先赋值再自增,保证a[0]存第一个值 i++; } Queue<int> qTwo; cout<<"Please enter the second queue of numbers in a growing order(press a zero if you want to stop): "<<endl; int b[siz]; int j = 0; // 索引变量移到循环外 while(1){ int n; cin>>n; if(!n) { cout<<"Ending the queue two's entry"<<endl; break; } qTwo.enqueue(n); b[j] = n; j++; } int n = qOne.size(); int m = qTwo.size(); int k = 0; int c[siz]; i = 0, j = 0; // 这里你原来的是直接合并后排序,也可以用有序队列双指针合并更高效,可自行替换 while(i < n) { c[k] = a[i]; i++; k++; } while(j < m) { c[k] = b[j]; j++; k++; } // 可以在这里加排序逻辑,再入队到qThree for(int i = 0; i < n+m; i++) { cout<<c[i]<<" "; } cout<<endl; for(int i = 0; i < n; i++) { cout<<a[i]<<" "; } cout<<endl; for(int i = 0; i < m; i++) { cout<<b[i]<<" "; } return 0; }
内容的提问来源于stack exchange,提问作者Northern Wind
相关产品推荐
相关产品推荐

