gpt4 book ai didi

C++ STL 堆栈弹出操作给出段错误

转载 作者:行者123 更新时间:2023-11-30 00:50:04 25 4
gpt4 key购买 nike

我实现了一个来自 this link 的编程问题在 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();
}

}

感谢您的帮助。

最佳答案

这一行

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

是导致段错误的原因。在尝试访问顶部之前,您必须检查堆栈是否为空,因为在空堆栈上调用 top 会调用 UB。

关于C++ STL 堆栈弹出操作给出段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26205633/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com