2013-04-11 85 views
0

我正在学习如何创建堆栈和链接列表。我正在编写的程序现在专注于模板堆栈类。当我制作了一堆int时,一切都很顺利,但是当我开始实施一堆char时,我的程序开始崩溃。具体来说,当我试图在char的堆栈上实现一个弹出式动作时,它开始搞乱了。堆栈char问题

你们可以请确认我是否正确地做了这件事,并让我知道我在做什么错了char堆栈?

这里是我的代码:

#include<iostream> 
using namespace std; 

#ifndef STACK_H 
#define STACK_H 

//STACK CLASS 
template<typename T> 
class Stack 
{ 
public: 
     Stack(int = 10); 
     ~Stack(){ delete stackPtr;}; 

     bool isEmpty() const 
     { return top == -1; } 

     bool isFull() const 
     { return top == size - 1; } 

     //push and pop 
     bool push(const T&); 
     bool pop(T&); 

private: 
     int size; 
     int top; 
     T *stackPtr; 
}; 

//CONSTRUCTOR 
template<typename T> 
Stack<T>::Stack(int newSize) 
    : top(-1), size(newSize), 
    stackPtr(new T[size]) //allocate array using ptr ******** 
{ 
    //empty constructor 
}; 

//PUSH VALUES ONTO STACK 
template<typename T> 
bool Stack<T>::push(const T &pushVal) 
{ 
    if(!isFull()) 
    { 
      stackPtr[++top] = pushVal; 
      return true;  
    } 

    return false; 
}; 

//POP VALUES OFF OF STACK 
template<typename T> 
bool Stack<T>::pop(T &popVal) 
{ 
    if(!isEmpty()) 
    { 
      popVal = stackPtr[top--]; 
      return true;    
    } 

    return false; 
}; 

#endif 

//DRIVER 
int main() 
{ 
    //STACK OF INT 
    Stack<int> intStack(5); 
    int intValue = 1; 

    cout << "Pushing values onto intStack: " << endl; 

    while(intStack.push(intValue)) 
    { 
     cout << intValue << ' '; 
     intValue++;        
    } 
    cout << "\nStack is full, cannot push..." 
     << endl << endl; 

    cout << "Popping values off of intStack: " << endl; 

    while(intStack.pop(intValue)) 
     cout << intValue << ' '; 

    cout << "\nStack is empty, cannot pop..." 
     << endl; 

    //STACK OF CHAR 
    Stack<char> charStack(5); 
    string greeting = "hello"; 
    int strSize = greeting.length(); 

    cout << "\nPushing values onto charStack: " << endl; 

    for(int i = 0; i < strSize; i++) 
    { 
     charStack.push(greeting.at(i)); 
     cout << greeting.at(i) << ' '; 
    }   

    cout << endl; 

    cout << "Popping values off of charStack: " << endl; 

    for(int i = (strSize - 1); i >= 0; i++) //PROBLEM OCCURS 
    { 
      charStack.pop(greeting.at(i)); 
      cout << greeting.at(i) << ' ';   
    } 

    system("pause"); 
} 

回答

3
for(int i = (strSize - 1); i >= 0; **i--**) //PROBLEM not anymore 
{ 
     charStack.pop(greeting.at(i)); 
     cout << greeting.at(i) << ' ';   
} 
+0

好吧,太棒了!那么除了一切看起来好吗? – 2013-04-11 18:44:55

+1

第一次看,是的,为了学校,而不是系统(“暂停”),你可以使用cin.get()。 – neagoegab 2013-04-11 18:46:53

+0

很酷。为什么比系统更好(“暂停”)?似乎系统(“暂停”)不那么草率。 – 2013-04-11 18:54:09

2

也许这不是您的特定问题的根源,但你真的应该使用 delete[] stackPtr 而不是delete stackPtr在你的析构函数。 Wikipedia explains why