2011-10-17 2 views
0

В моем коде я пытаюсь найти конкретный элемент, помещенный в стек. Для этого я перемещаю все элементы в стек temp, чтобы вытащить его из исходного стека. После того, как он выскочил, я должен переместить все элементы в исходный стек в исходном порядке. Мой код никогда не распознает, что элемент находится в стеке, поэтому я его не обнаружил, когда он действительно находится в стеке. Можете ли вы помочь мне отлаживать цикл ...Поиск одного предмета в стеке

ИНТ главная:

#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.isempty(); 
      temp = s.pop(); 
      if(s.isempty() && temp.color == g.color) 
      { 
       cout << "The " << g.color << " gumball has been eaten." << endl << endl; 
      } 

С этого момента, я считаю, это ошибка:

  while(!s.isempty() && g.color != temp.color) 
      { 
       gumballStack.push(temp); 
       g.counter++; 
       s.pop(); 
       cout << " " << temp.counter << endl << endl; 
      } 
      if(!s.isempty()) 
      { 
       cout << "The " << " " << g.color << " gumball has been eaten." << endl << endl; 
      } 
      else 
      { 
       cout << "The gumball cannot be 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; 
} 

заголовочных файла:

#ifndef STACK_H 
#define STACK_H 
#include "Gumball.h" 

// Interface file - Stack class definition 
class Stack { 
    public: 
     Stack(); 
     void push(Gumball); 
     Gumball pop(); 
     bool isempty(); 
     bool isfull(); 
    private: 
     Gumball gumballs[6+1]; 
     int top; 
}; 


#endif // STACK_H 

ОТВЕТЬТЕ ВАШ ВОПРОС @TOM:

хорошо .cpp (для stack.h), я думаю, что он ответит на большинство вопросов, которые вы просили:

#include "Stack.h" 
#include "Gumball.h" 

using namespace std; 

// Constructor to initialize the stack 
Stack::Stack() 
{ 
    top = -1; 
} 

// Function to add item x to stack 
void Stack::push(Gumball x) 
{ 
    if(!isfull()){ 
    top++; 
    gumballs[top] = x; 
    return; } 
    else 
    return; 
} 

// Function to remove and return top item of stack 
Gumball Stack::pop() 
{ 
    Gumball x; 

    if(!isempty()) { 
     x = gumballs[top]; 
     top--; 
     return x; } 
    else 
     return x; 
} 

// Function to check if stack is empty 
bool Stack::isempty() 
{ 
    if (top == -1) 
     return true; 
    else 
     return false; 
} 

// Function to check if stack is full 
bool Stack::isfull() 
{ 
    if (top == 6) 
     return true; 
    else 
     return false; 
} 

Я вижу проблему вы заявил, что я ставлю температуру на стек много раз ... определенно не мои намерения, спасибо за указание на это. Как получить его, чтобы добавить каждый gumball в стек, который не равен элементу, который я ищу, вместо того же?

Я думаю, добавив Gumball.h и .cpp ответит ур другие вопросы так вот:

gumball.h файл:

#ifndef GUMBALL_H 
#define GUMBALL_H 
#include <iostream> 

using namespace std; 

// Interface file - Gumball class definition 
class Gumball 
{ 
    public: 
     Gumball(); 
     string color; 
     int counter; 
    private: 
}; 

#endif // GUMBALL_H 

gumball.cpp файл:

#include "Gumball.h" 

Gumball::Gumball() 
{ 
    color = " "; 
    counter = 0; 
} 
+0

Почему бы не использовать STL контейнер? –

ответ

1

Это должно быть

while(!s.isempty() && g.color != temp.color) 
     { 
      gumballStack.push(temp); 
      g.counter++; 
      temp = s.pop(); //temp has been updated 
      cout << " " << temp.counter << endl << endl; 
     } 

но обратите внимание, что этот код не будет работать, когда съедено Gumball является последним в стеке, потому что s будет пустым.

Кроме согласования с томом и указывая вам в размышлении о других решениях (УВО :: список, например), вы должны использовать что-то вроде этого

if (s.isempty()) { 
    cout << "The gumball cannot be found." << endl << endl; 
} 
while(!s.isempty()) { 
    Gumball temp = s.pop(); 
    if(temp.color == g.color) { 
     cout << "The " << " " << g.color << " gumball has been eaten." << endl << endl; 
    } else { 
     gumballStack.push(temp); 
     g.counter++; 
     if (s.isempty()) { 
      cout << "The gumball cannot be found." << endl << endl; 
     } 
    } 
} 
while(!gumballStack.isempty()) { 
     s.push(gumballStack.pop()); 
     gumballStack.pop(); 
} 
1

Сложно сказать, в чем проблема, не видя реализации Stack. Однако, поскольку я нашел несколько частей вашего кода запутанным, я подумал, что вам может быть полезно указать, где. Если вы измените интерфейс на свой код, чтобы он был понятнее, возможно, ваши проблемы станут очевидными.

// Interface file - Stack class definition 
class Stack { 
    public: 
     Stack(); 
     void push(Gumball); //Does this push to the front or back? 
          // The stl uses push_back, and push_front, 
          // its good to keep this convention 
     Gumball pop(); //Does this pop the front or back? 
     bool isempty(); //This function doesn't change Stack, right? 
         // if so it should be marked const. 
     bool isfull(); //Mark as const? 
    private: 
     Gumball gumballs[6+1]; 
     int top; 
}; 

Из приведенных выше вопросов, то const ность isempty() особенно важно в дальнейшем

case 'E': 
    s.isempty(); //This should be redundent? 
       // isempty is a question, it shouldnt change s. 
    temp = s.pop(); 
    if(s.isempty() && temp.color == g.color) 
    { 
    cout << "The " << g.color << " gumball has been eaten." << endl << endl; 
    } 
    //Here isempty is being used as a question (as if it doesn't change s 
    // - I presume this is the intended use. 
    //Also, .color is not a function, it should be, as will be seen. 
    //Also, temp never gets updated in your loop. 
    while(!s.isempty() && g.color != temp.color) 
    { 
    gumballStack.push(temp); //Why are you pushing multiple copies 
           // of the same temp 
    g.counter++; //The counter should be an implementation detail, 
     // it should not be exposed like this. 
     // perhaps overload operator++()? 
     //Presumably you want g.color to update when you increase the counter? 
     //this doesn't currently happen because g.color is not a function - 
     // it points to data. 
     //I'm guessing that When you call color(), 
     // the function should check the value of the counter 
     // and obtain the appropriate color. 
    s.pop(); //Did you want to update temp here? 
    cout << " " << temp.counter << endl << endl; 
    } 

В идеале, вы бы переписать всю вещь с итераторы. Посмотрите на интерфейс для std::find.

+0

Я ответил на ваши вопросы и так далее в том же сообщении.Просто прокрутите вниз, чтобы увидеть изменения. Кроме того, было предпочтительнее, чтобы я не использовал std :: find или итераторы еще ... – 123me

Смежные вопросы