2014-10-05 36 views
1

我在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(); 
     } 

} 

感謝您的幫助。

+1

在while循環中更改您的支票順序。首先檢查堆棧是否爲空,然後嘗試取頂部。 ;-) – Xarn 2014-10-05 18:06:17

+1

是的,我也會改變這個順序:如果堆棧是空的沒有意義檢查頂部元素 – 2014-10-05 18:07:43

+1

也許使用堆棧發佈在該鏈接上的解決方案也不正確。分析它! – P0W 2014-10-05 18:08:25

回答

6

此行

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

是什麼原因造成的段錯誤。在嘗試訪問頂層之前,您必須檢查堆棧是否爲空,因爲在空堆棧上調用top會調用UB。

0

在空容器上調用pop_back未定義。 std::stack使用std::deque默認情況下,看到std::deque::pop_back