C++;STL堆栈pop操作导致分段错误 我从C++中实现了一个编程问题,但在代码< >代码()中,我得到了一个分割错误。我对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(); } } #包括 #包括 使用名称空间std; 无效打印(int*arr); int main(){ int arr[]={1,4,2,6,3,8,7,2,6}; printNge(arr); 返回0; } 无效打印行(内部*arr){ 斯塔克街; 圣普什(arr[0]); 对于空容器上的(int i=1;i

C++;STL堆栈pop操作导致分段错误 我从C++中实现了一个编程问题,但在代码< >代码()中,我得到了一个分割错误。我对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(); } } #包括 #包括 使用名称空间std; 无效打印(int*arr); int main(){ int arr[]={1,4,2,6,3,8,7,2,6}; printNge(arr); 返回0; } 无效打印行(内部*arr){ 斯塔克街; 圣普什(arr[0]); 对于空容器上的(int i=1;i,c++,stl,segmentation-fault,stack,C++,Stl,Segmentation Fault,Stack,调用pop_back未定义。std::stack默认使用std::deque,请参阅:在空容器上调用pop_back未定义。std::stack默认使用std::deque,请参阅:此行 while((st.top() < arr[i]) && (!st.empty())) { while((st.top()

调用
pop_back
未定义。
std::stack
默认使用
std::deque
,请参阅:

在空容器上调用
pop_back
未定义。
std::stack
默认使用
std::deque
,请参阅:

此行

while((st.top() < arr[i]) && (!st.empty())) {
while((st.top()
是导致segfault的原因。在尝试访问top之前,必须检查堆栈是否为空,因为空堆栈上的caling
top
调用UB。

此行

while((st.top() < arr[i]) && (!st.empty())) {
while((st.top()

是导致segfault的原因。在尝试访问top之前,您必须检查堆栈是否为空,因为空堆栈上的caling
top
调用UB。

更改while循环中的检查顺序。首先检查堆栈是否为空,然后尝试获取top是的,我也会改变顺序:如果堆栈是空的,那么检查顶部元素没有意义。可能使用堆栈在链接上发布的解决方案也不正确。分析它!是的!我刚刚重新阅读了我的问题,发现了错误。请发布一个答案,我将接受你的答案。使用所有警告和调试信息编译(
g++-Wall-g
)。仔细阅读的文档。使用调试器(
gdb
)更改while循环中的检查顺序。首先检查堆栈是否为空,然后尝试取顶部。;-)是的,我也会改变顺序:如果堆栈是空的,那么检查顶部元素没有意义。可能使用堆栈在链接上发布的解决方案也不正确。分析它!是的!我刚刚重新阅读了我的问题,发现了错误。请发布一个答案,我将接受你的答案。使用所有警告和调试信息编译(
g++-Wall-g
)。请仔细阅读的文档。使用调试器(
gdb