[英]C++ STL stack pop operation giving Segment fault though I checked for empty stack
我在 S[position] 堆棧上執行了彈出操作,它給出了段錯誤,但頂部操作給出了沒有任何錯誤的結果,並且在彈出操作之前也執行了空檢查。
無法弄清楚是什么導致了問題。
#include<iostream>
#include<stack>
#include<stdlib.h>
using namespace std;
int main(){
int bar,position;
cout<<"Enter the number of bars: ";cin>>bar;
cout<<"Enter the position of the bar where you want to place: ";cin>>position;
position = position - 1;
stack<int> S[bar];
for(int i = bar; i>0; i--){
S[0].push(i);
}
S[0].pop();
for(int i = 1; i<bar; i++){
if(i == position){
S[i].push(1);
continue;
}
S[i].push(S[0].top());
S[0].pop();
}
for(int i = 1; i< bar; i++){
if(S[i].top() == 2){
if(!S[position].empty()){
cout<<S[position].top();
S[position].pop(); //This line generating segment fault
}
}
}
}
Output:
Enter the number of bars: 3 Enter the position of the bar where you want to place: 2 Segmentation fault (core dumped)
1.您可以使用一個庫 - bits/stdc++.h。 這個庫包含幾乎所有的庫。
#include <bits/stdc++.h>
2.如果bars=b,堆棧有k個元素,0-k-1,你go在1.你必須go在0上,或者用k+1個元素組成堆棧。
stack<int> s[k+1] and for(long long i=1 ; i<=bar ; i++);
或者
for(i=0 ; i<bars ; i++)
3.真正的錯誤——你要找的不是你想的順序。 當您檢查其值時,該錯誤在線。 線:
if(S[i].top() == 2)
錯誤在這里,因為您不確定此堆棧是否為空。 你檢查堆棧[位置]。 如果堆棧為空並且您 get.pop() 或 .top() 編譯器會給您分段錯誤(核心轉儲)。 在我看來,您對在哪里寫 i 和 position 感到困惑,但檢查 - .S[i].empty()
必須在if(S[i] == 2)
之前。 或者你只需要檢查帶有索引 i 的堆棧,如果它是空的。 更改后,代碼如下所示:
#include<bits/stdc++.h>
使用命名空間標准;
int main(){ int bar,position;
cout<<"Enter the number of bars: ";cin>>bar;
cout<<"Enter the position of the bar where you want to place: ";cin>>position;
position = position - 1;
stack<int> S[bar];
for(int i = bar; i>0; i--){
S[0].push(i);
}
S[0].pop();
for(int i = 0; i<bar; i++){
if(i == position){
S[i].push(1);
continue;
}
S[i].push(S[0].top());
S[0].pop();
}
/*
for(int i = 0; i < bar; i++){
if( !S[i].empty() ){
if(S[i].top() == 2){
cout<<S[i].top();
S[i].pop();
}
}
}
OR
*/
for(int i = 0; i < bar; i++){
if( !S[i].empty() ){
if(S[i].top() == 2){///this line gave you a segmentation fault (core dumped)
if(!S[position].empty()){
cout<<S[position].top();
S[position].pop();
}
}
}
}
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.