c++ - 从堆栈中弹出时出现分段错误
问题描述
任何人都可以帮助我找出此代码的错误吗?这是一个hackerrank问题MAXIMUM ELEMENT。对于案例 2,“maxes.pop()”行一直给我分段错误。注释掉该行实际上允许代码编译。
问题:
您有一个空序列,您将收到查询。每个查询都是以下三种类型之一:
1 x - 将元素 x 推入堆栈。
2 - 删除存在于堆栈顶部的元素。
3 - 打印堆栈中的最大元素。
功能说明
在下面的编辑器中完成 getMax 函数。
getMax 有以下参数:
- 字符串操作[n]:作为字符串的操作
退货
- int[]:每个类型 3 查询的答案
输入格式
输入的第一行包含一个整数, 。接下来的每一行都包含一个上面提到的查询。
约束
约束
所有查询均有效。
样本输入
STDIN Function
----- --------
10 operations[] size n = 10
1 97 operations = ['1 97', '2', '1 20', ....]
2
1 20
2
1 26
1 20
2
3
1 91
3
样本输出
26
91
vector<int> getMax(vector<string> operations) {
stack<int> nums;
stack<int> maxes;
vector<int> maxnums;
int max = INT_MIN;
//int top = -1;
for(long unsigned int i=0; i<operations.size(); i++){
switch(operations[i][0]){
case('1'):
cout<<"Operation 1"<<endl;
nums.push(stoi(operations[i].substr(2)));
if(nums.top() > max){
max = nums.top();
maxes.push(max);
}
break;
case('2'):
cout<<"Operation 2"<<endl;
if(max==nums.top()){
//cout<<"top element in maxes"<<maxes.top()<<endl;
maxes.pop();
max = maxes.top();
}
nums.pop();
break;
case('3'):
cout<<"Operation 3"<<endl;
maxnums.push_back(maxes.top());
break;
}
}
return maxnums;
}
解决方案
考虑以下输入序列:
1 1 // push 1. Pushes 1 into nums and maxes
1 1 // push 1. Pushes 1 into nums, but not into maxes, since max = 1.
3 // delete top stack element
3 // delete top stack element
在处理第一3
行之前,您的状态将是:
nums = {1, 1}
maxes = {1}
max = 1
现在,在第一次弹出时,一切都会好起来的,所以在第一次弹出后,您最终会得到以下状态:
nums = {1}
maxes = {}
max = 1
但是,在第二次弹出时,max == nums.top()
仍然是正确的,因此您从maxes
已经为空的堆栈中弹出。这就是为什么它会给你分段错误。
推荐阅读
- python - 如何在时域计算音高基频 f( 0) )?
- python - 创建一个表格,显示列表是否包含在数据框的分组列中
- java - 如何使用来自 url 的共享图像方法
- python - 当镜像关闭时,如何安全地交换基础 docker 镜像?
- java - 扫描并检查二进制数
- python - 将元组变量作为参数传递给函数
- javascript - 为什么 Chrome 在执行 Javascript 之前看起来像是在等待 DOM?
- php - 如果我们在 if 条件中设置它们,PHP 会话变量将不起作用
- dart - RangeError:无效值:不在范围 0..1114111 内,包括:-1 尝试使用升级命令时
- flutter - 在 Flutter 中将本地化更改为阿拉伯语时,小部件方向不会更改为 RTL