基本上,在这个案例循环中:e / E ..我的目标是将一个项目从原始堆栈中弹出,将其存储在临时的口香糖中,然后查看该临时口香糖的颜色区域。如果这是我想要的那么我有一个匹配,其计数器增加。如果没有,将口香糖球推到临时堆栈上。然后重复此过程,直到找到我想要的或原始堆栈为空。此外,当每个口香糖被吃掉时,要打印它被移动了多少次,因为它阻塞了其他口香糖球。当我说吃饭时,它说没有找到,我不明白为什么。有什么建议??
我的主要看起来像这样(我遇到问题的循环是e):
#include <iostream>
#include "Stack.h"
#include "Gumball.h"
using namespace std;
int main()
{
Stack s, gumballStack;
Gumball g, temp;
char choice;
bool choice_flag = true;
do {
cin >> choice;
cin >> g.color;
switch(choice)
{
case 'b':
case 'B':
cout << "A" << " " << g.color << " gumball has been bought." << endl << endl;
g.counter = 0;
s.isempty();
s.push(g);
if(!s.isfull())
cout << "The gumball is" << " " << g.color << " and has been stored." << endl << endl;
else
cout << "There is no room for another gumball." << endl << endl;
break;
case 'e':
case 'E':
//s.pop();
s.pop() = temp;
while(!s.isempty() && temp.color != g.color)
{
s.pop().counter++;
gumballStack.push(temp);
s.pop();
cout << " " << g.counter << endl;
}
if(!s.isempty())
{
//cout << " " << g.counter++ << endl;
s.pop();
cout << "A gumball has been eaten." << endl << endl;
// cout << "A" << " " << g.color << " was not found." << endl << endl;
}
else
{
cout << "A" << " " << g.color << " was not found." << endl << endl;
}
while(!gumballStack.isempty())
{
gumballStack.pop();
s.push(gumballStack.pop());
gumballStack.pop();
}
break;
case 'q':
case 'Q':
choice_flag = false;
break;
}
} while(choice_flag);
return 0;
}
答案 0 :(得分:0)
您的代码存在一些问题(抱歉粗鲁):1。您可以使用std :: vector,它可以实现与您想要的堆栈相同的功能; 2.如果你必须选择使用堆栈,请使用std :: stack,它可能比你自己的实现更优秀; 3.根据您的要求,您应该使用std :: count_if算法或std :: find_if定义一个谓词,这将使您的代码更紧凑和美观。