问题
I implemented a programming question from this link in C++ but I am getting a segmentation fault in the pop()
operation with my code. I am fairly new to C++ and can not seem to find the error myself.
#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();
}
}
Thanks for the help.
回答1:
This line
while((st.top() < arr[i]) && (!st.empty())) {
is what is causing the segfault. You have to check the stack for being empty before you try to access top, as caling top
on empty stack invokes UB.
回答2:
Calling pop_back
on an empty container is undefined. std::stack
uses std::deque
by default, see std::deque::pop_back:
来源:https://stackoverflow.com/questions/26205633/c-stl-stack-pop-operation-giving-segmentation-fault