Nar*_*aki 1 c++ stack stl segmentation-fault
我在C++ 中用这个链接实现了一个编程问题,但是pop()我的代码在操作中遇到了分段错误.我是C++的新手,似乎无法自己找到错误.
#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();
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢您的帮助.
这条线
while((st.top() < arr[i]) && (!st.empty())) {
Run Code Online (Sandbox Code Playgroud)
是导致段错误的原因.在尝试访问top之前,必须检查堆栈是否为空,因为top空堆栈上的调用会调用UB.
| 归档时间: |
|
| 查看次数: |
3346 次 |
| 最近记录: |