C++ STL堆栈弹出操作给出了段错误
问题描述:
我在C++中实现了一个this link的编程问题,但是我的代码在pop()
操作中遇到了段错误。我对C++相当陌生,似乎无法自己发现错误。C++ STL堆栈弹出操作给出了段错误
#include<iostream>
#include<stack>
using namespace std;
void printNge(int *arr);
int main() {
int arr[] = {1,4,2,6,3,8,7,2,6};
printNge(arr);
return 0;
}
void printNge(int *arr) {
stack<int> st;
st.push(arr[0]);
for(int i=1; i<9;i++) {
while((st.top() < arr[i]) && (!st.empty())) {
cout << "Element is:" << st.top() << " NGE is:" << arr[i] << endl;
cout << "Removing element: " << st.top() << endl;
st.pop();
}
cout << "Pushing element: " << arr[i] << endl;
st.push(arr[i]);
}
while(!st.empty()) {
cout << "Element is:" << st.top() << " NGE is:" << -1 << endl;
st.pop();
}
}
感谢您的帮助。
答
此行
while((st.top() < arr[i]) && (!st.empty())) {
是什么原因造成的段错误。在尝试访问顶层之前,您必须检查堆栈是否为空,因为在空堆栈上调用top
会调用UB。
在while循环中更改您的支票顺序。首先检查堆栈是否为空,然后尝试取顶部。 ;-) – Xarn 2014-10-05 18:06:17
是的,我也会改变这个顺序:如果堆栈是空的没有意义检查顶部元素 – 2014-10-05 18:07:43
也许使用堆栈发布在该链接上的解决方案也不正确。分析它! – P0W 2014-10-05 18:08:25