[英]Template Stack and LIFO C++
因此,我試圖了解模板以及Fifo和Lifo堆棧內容。 我一直在處理一些與此相關的代碼,並且我可以獲取int數據來做我想測試的事情,但是我一生都無法弄清楚如何使它與字符串一起工作。 我擁有代碼的方式不斷使我崩潰,但是沒有給我任何錯誤,所以我認為我會在這里彈出,看看是否有人可以告訴我我在做什么錯。 這是我的代碼:
-----------//my header//---------------------
#include <stdlib.h>
#include <iostream>
#include <string>
#ifndef STACK_H_
#define STACK_H_
template<class T>
class StackTest
{
private:
unsigned int maxSize;
T *stackData;
int top;
public:
StackTest(int size){
stackData = new T[size];//to hold the T type data items
top = -1;//no items on the stack
maxSize = size;//set maximum size that stack can hold
}
virtual ~StackTest(){}
int count(){
return top + 1;
}
bool isEmpty(){
return top == -1 ? true : false;
}
bool isFull(){
return top == maxSize - 1 ? true : false;
}
T* peek(){
if(!isEmpty())//check for empty
return &stackData[top - 1];
}
T* pop(){
if(!isEmpty()){
top -= 1;//decrease the top by 1 to indicate the delete
return &stackData[top];//return deleted item
}
return NULL;
}
void push(T* item){
stackData[top++] = *item;//insert to data array and increase the top by one
}
};
#endif /* STACK_H_ */
-----------//my main//---------------
#include <iostream>
#include <string>
#include "Pair.h"
using namespace std;
int main() {
int dataTest;
string strTest;
StackTest<int> intStack(10);
StackTest<string> stringStack(50);
//Insert data into the stack
dataTest = 3;
intStack.push(&dataTest);
dataTest = 4;
intStack.push(&dataTest);
dataTest = 5;
intStack.push(&dataTest);
dataTest = 6;
intStack.push(&dataTest);
strTest = "test";
stringStack.push(&strTest);
//Show the top item
cout << *intStack.peek() << endl;
cout << *stringStack.peek() << endl;
//Pull the top item out (twice)
intStack.pop();
intStack.pop();
//Show the new top item
cout << *intStack.peek() << endl;
return 0;
}
因此,如果有人想給我一些指導,我將非常感激,謝謝。
您的實現存在一些問題。 最微妙的之一是push()
成員函數:
void push(T* item){
stackData[top++] = *item; //insert to data array and increase the top by one
// ^^
// You want pre-increment here!
}
這將遞增top
並使用舊值作為stackData
的索引。 由於堆棧為空時top
為-1
,因此您的程序實際上正在執行:
stackData[-1] = *item;
top = 0;
不用說,第一次分配會導致未定義的行為。
不確定行為的另一個來源是peek()
成員函數,該函數在堆棧為空時不返回任何內容:
T* peek(){
if(!isEmpty())//check for empty
return &stackData[top - 1];
}
根據C ++ 11標准的6.6.3 / 2段:
[...]從函數的結尾流出就等於沒有值的返回; 這導致返回值函數中的行為不確定。
但這不是唯一的問題:另一個問題是訪問stackData
:
return &stackData[top - 1];
當top
不等於或大於1時,這也會導致未定義的行為,因為您將獲取位於數組負地址中的(非)對象的地址。
另外,我建議重寫isEmpty()
和isFull()
,如下所示:
bool isEmpty(){
return (top == -1);
}
bool isFull(){
return (top == maxSize - 1);
}
作為一般建議,請考慮在堆棧為空時不要將值-1
用於top
。 正如Ben Voigt在評論中提到的那樣 ,這會導致您出現許多不一的錯誤。
另外, 正如DyP所指出的那樣 ,析構函數不會釋放在構造函數中分配的內存,因此您的StackTest
對象正在泄漏內存。 然后,既然如此,您可能想要看一看所謂的“三規則” ,即您的程序將被違反。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.