嗨,我正在尝试查找小于或等于当前塔数的先前塔数,此解决方案对于输入(NumOfTowers) 10,代码将在segfault中运行,我无法在这里看到问题,
#include <iostream>
#include <stack>
using namespace std;
int main()
{
std::stack<int> Towers; //for storing the Height of the towers
std::stack<int> TempTowers; // Temrory buffer stack
std::stack<int> CountTowers; //for storing the count of all previous
towers less than the current one
unsigned int NumTestCases,NumOfTowers,i,j,count=1,temp,temp_height;
cin>>NumTestCases;
cin>>NumOfTowers;
while(NumTestCases){
while(!Towers.empty()){
Towers.pop();
}
for(i=0;i<NumOfTowers;i++){
cin>>temp;
Towers.push(temp);
}
for(i=0;i<NumOfTowers-1;i++){
count=1;
temp_height=Towers.top();
Towers.pop();
temp=Towers.top();
while(temp<temp_height){
count++;
TempTowers.push(temp);
Towers.pop();
temp=Towers.top();
}
CountTowers.push(count);
while(!TempTowers.empty()){
temp=TempTowers.top();
TempTowers.pop();
Towers.push(temp);
}
}
NumTestCases--;
cout<<"1"<<" ";
while(!CountTowers.empty()){
cout<<CountTowers.top()<<" ";
CountTowers.pop();
}
cout<<"\n";
}
}
任何帮助都会很棒。
最佳答案
改变这个
while(temp<temp_height){
count++;
TempTowers.push(temp);
Towers.pop(); // Popped the last element
temp=Towers.top(); // no more elements left
}
对此
while(!Towers.empty() && Towers.top() < temp_height)
{
++count;
TempTowers.push(Towers.top());
Towers.pop();
}
问题不在于输入的长度,而在于输入的顺序。如果
I/p = {1, 2, 3, 4}
您的代码尝试访问空堆栈的top()
时将给出错误。关于c++ - 查找以前的塔数少于或等于当前的塔数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46883974/