在堆栈中搜索值并存储在临时堆栈中
Searching Stack for value and Storing in Temp Stack
基本上,在这个循环中:e/e ..我的目标是从原始堆栈中弹出一个项目,将其存储在临时gumball中,然后查看该临时gumball的颜色字段。如果它是我想要的,那么我就有一个匹配,它的计数器就会增加。如果不是,则将gumball推入临时堆栈。然后重复这个过程,直到我找到我想要的或者原来的堆栈是空的。此外,当每个口香糖被吃掉时,打印它被移动了多少次,因为它挡住了其他口香糖。当我说吃的时候,它说没找到,我不明白为什么。有什么建议吗? ?
我的主程序看起来像这样(我遇到问题的循环是在情况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;
}
你的代码有一些问题(很抱歉是粗鲁的):你可以使用std::vector,它可以实现与堆栈相同的功能;2. 如果你必须选择使用堆栈,使用std::stack,它可能比你自己的实现性能更好;3.根据您的需求,您应该使用std::count_if算法或std::find_if定义一个谓词,这将使您的代码更加紧凑和美观。
相关文章:
- C++ 在堆栈中包含多态属性的类对象存储
- 是否可以检查存储在堆栈上的单词是否是回文,而C++中没有任何附加数据结构
- 指向存储在堆栈中的变量的指针
- Boost::序列化存储结构时的堆栈溢出错误
- 存储在存储在堆栈中的堆与矩阵中的矩阵可以看作是一系列指针
- 作用域存储在堆栈中
- 优化易失性堆栈变量的存储/构造是否合法
- 是放置在存储在堆栈或堆中的unordered_map中的项目
- 除了堆栈和堆模型之外,还为C++实现了哪些其他形式的自动和动态存储
- 使用堆栈存储对象
- 存储在对象向量上的基于堆栈的指针具有很长的使用寿命
- 将地址存储到矢量中的堆栈分配对象
- C++对象存储在堆栈或堆中
- 为什么存储在 STL 向量中的堆栈分配元素C++即使超出范围也仍然处于活动状态
- 当对象不使用 new 关键字但父对象在堆中时,对象是否存储在堆栈或堆中
- 堆栈/堆变量的变量/引用名称或类型存储在内存中的位置
- 为什么这不会导致堆栈溢出?其中是存储的全局向量(堆栈或堆)
- 我将如何在C++03中便携地实现对齐堆栈存储
- 是存储在堆栈上的对象
- 小对象堆栈存储,严格混叠规则和未定义行为