我正在學習如何創建堆棧和鏈接列表。我正在編寫的程序現在專注於模板堆棧類。當我製作了一堆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");
}
好吧,太棒了!那麼除了一切看起來好嗎? – 2013-04-11 18:44:55
第一次看,是的,爲了學校,而不是系統(「暫停」),你可以使用cin.get()。 – neagoegab 2013-04-11 18:46:53
很酷。爲什麼比系統更好(「暫停」)?似乎系統(「暫停」)不那麼草率。 – 2013-04-11 18:54:09