我在堆栈的 C++ 代码中收到"timeout: the monitored command dumped core"错误



有stk0, stk1和stk2 3个堆栈。为了区分push和pop,程序对3个堆栈使用push0, push1和push2,类似地使用pop0, pop1和pop2。程序以stop0, stop1或stop2结束,并显示stack0, stack1或stack2的内容,然后退出。我的代码在所有测试用例中都工作得很好,接受我下面提到的那个。

#include <iostream>
#include <stack>
using namespace std;
int main() {
stack<string> stk0;
stack<string> stk1;
stack<string> stk2;
while(true) {
string a;
cout<<"Give one of options: pop, push, stopn";
cin >> a;
if(a=="push0") {
string b;
cin >> b;
stk0.push(b);
}
else if(a=="push1") {
string b;
cin >> b;
stk1.push(b);
}
else if(a=="push2") {
string b;
cin >> b;
stk2.push(b);
}
else if(a=="pop0") {
if(!stk0.empty()) {
string b = stk0.top();
stk0.pop();
cout<<"Element popped from stack 0 is: "<<b<<endl;
}
else cout<<"Underflow in stack 0n";
}
else if(a=="pop1") {
if(!stk1.empty()) {
string b = stk1.top();
stk1.pop();
cout<<"Element popped from stack 1 is: "<<b<<endl;
}
else cout<<"Underflow in stack 1n";
}
else if(a=="pop2") {
if(!stk2.empty()) {
string b = stk2.top();
stk2.pop();
cout<<"Element popped from stack 2 is: "<<b<<endl;
}
else cout<<"Underflow in stack 2n";
}
else if(a=="stop0") {
while(!stk0.empty()) {
cout<<stk0.top()<<endl;
stk0.pop();
}
break;
}
else if(a=="stop1") {
while(!stk0.empty()) {
cout<<stk1.top()<<endl;
stk1.pop();
}
break;
}
else if(a=="stop2") {
while(!stk2.empty()) {
cout<<stk2.top()<<endl;
stk2.pop();
}
break;
}
}
}

当我输入

push0阿格拉push1斋浦尔push0勒克瑙push2博帕尔push1阿杰梅尔push1Udaipur pop0 pop1 push2 Indore push0 Meerut stop1

i gettimeout:被监控的命令转储内核错误。

看看这部分代码:

else if(a=="stop1") {
while(!stk0.empty()) {
cout<<stk1.top()<<endl;
stk1.pop();
}
break;
}

astop1时,循环将继续旋转,并弹出stk1并打印其值,但由于条件为!stk0.empty()而不是!stk1.empty(),因此循环不会退出。

你可能想这样做:

else if(a=="stop1") {
while(!stk1.empty()) { // <- Notice change from 'stk0.empty()' to 'stk1.empty()'
cout<<stk1.top()<<endl;
stk1.pop();
}
break;
}

相关内容

最新更新