开发者

Searching Stack for value and Storing in Temp Stack

Basically, within this loop in the case:e/E .. I am aiming to pop an item off the original stack, storing it in a temporary gumball, then look at the color field of that temporary gumball. If it is what I want then I have a match and its counter is increased. If not, push the gumball onto the temporary stack. Then repeat this process until I've found what I want or the original stack is empty. Additionally, when each gumball is eaten, to print how many times it has been moved because it was blocking other gumballs. When I say to eat, it says not found and i cant see why. Any suggestions??

My main looks like this(the loop I am having problems with is in case 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 roo开发者_JAVA百科m 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;
}


Your code has some problems(sorry to be rude): 1. you can use a std::vector which can achieve the same functionality as stack you want; 2. if you must choose to use a stack, use a std::stack which may outperformace than your own implementation; 3. based on your requirement, you should define a predicator using std::count_if algorithm or std::find_if which would make your code more compact and beautiful.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜