在堆栈中搜索值并存储在临时堆栈中

Searching Stack for value and Storing in Temp Stack

本文关键字:堆栈 存储 搜索      更新时间:2023-10-16

基本上,在这个循环中: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定义一个谓词,这将使您的代码更加紧凑和美观。