访问堆栈和队列时发生运行时错误
Runtime error accessing stacks and queues
我正在做UVa在线评委问题-11995。调试后,我发现一些东西让我感到困惑。
这是我调试代码之前的部分,我得到了一个"运行时错误"。
int take;
scanf("%d", &take);
int out_s;
int out_q;
int out_p;
if(sta){
out_s = s.top();
if(!s.empty() && out_s == take) s.pop();
else sta = 0;
}
if(que){
out_q = q.front();
if(!q.empty() && out_q == take) q.pop();
else que = 0;
}
if(pri){
out_p = p.top();
if(!p.empty() && out_p == take) p.pop();
else pri = 0;
}
在我简单地删除了一些愚蠢的整数赋值后,我得到了一个"已接受"的
int take;
scanf("%d", &take);
if(sta){
if(!s.empty() && s.top() == take) s.pop();
else sta = 0;
}
if(que){
if(!q.empty() && q.front() == take) q.pop();
else que = 0;
}
if(pri){
if(!p.empty() && p.top() == take) p.pop();
else pri = 0;
}
我真的不明白为什么我会因为变量的分配而出现运行时错误。
这是我的全部代码:
using namespace std;
int main ()
{
int n;
while(scanf("%d", &n) != EOF){
int comm;
stack<int> s;
queue<int> q;
priority_queue<int> p;
bool sta = 1;
bool que = 1;
bool pri = 1;
for(int i = 0; i < n; i++){
scanf("%d", &comm);
if(comm == 1){
int input;
scanf("%d", &input);
s.push(input);
q.push(input);
p.push(input);
}
else{
int take;
scanf("%d", &take);
int out_s;
int out_q;
int out_p;
if(sta){
out_s = s.top();
if(!s.empty() && out_s == take) s.pop();
else sta = 0;
}
if(que){
out_q = q.front();
if(!q.empty() && out_q == take) q.pop();
else que = 0;
}
if(pri){
out_p = p.top();
if(!p.empty() && out_p == take) p.pop();
else pri = 0;
}
}
}
if(sta == 1 && que == 0 && pri == 0) printf("stackn");
else if(sta == 0 && que == 1 && pri == 0) printf("queuen");
else if(sta == 0 && que == 0 && pri == 1) printf("priority queuen");
else if(sta == 0 && que == 0 && pri == 0) printf("impossiblen");
else printf("not suren");
}
return 0;
}
out_s = s.top();
if(!s.empty() && out_s == take) s.pop();
在这里,您首先访问堆栈的顶部元素,然后才检查堆栈是否真的包含任何内容。
在修改后的代码中,top()
调用由empty()
和逻辑和保护,因此在容器为空时不会发生。
相关文章:
- 删除指向指针的指针是运行时错误吗
- c++中的指针和运行时错误
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 在同一模拟中使用静脉和静脉_ inet内容时出现运行时错误
- 对单向链表进行排序时出现运行时错误
- 为什么此代码存在运行时错误?
- 你能解释一下什么运行时错误是如何解决它的吗?
- 为什么会出现 gettnig 运行时错误:加载类型为"_Bit_type"(stl_bvector.h) 的空指针?
- 为什么程序在 c++ 中迭代 emtpy 向量时会抛出运行时错误
- 更改运行时优先级队列的排序功能
- 运行时错误:引用绑定到类型为"int"的空指针
- 为什么当 vector 为空时会显示运行时错误?
- C++运行时错误与快速排序算法抛出堆栈转储错误
- 运行时错误:矢量下标超出范围:正在检查空集
- 分配给gslice_array会导致运行时错误
- cout 新创建的对象引发运行时错误
- C++在使用std::multimap时出现运行时错误的几率很小
- 使用节点的深度复制队列运行时错误
- 访问堆栈和队列时发生运行时错误
- c++对象指针的优先级队列在运行时错误为无效堆