我对C ++很新,因此尝试从我对Java的知识实现堆栈ADT。这是我的头文件
#include <iostream>
#include <cstdlib>
template <class S>
class stack{
public:
Stack(const int): size_(size), top(-1){
if(size_>0){
this->size_ = size;
}else{
std::cout<<"Stack can be initialized by values greater than 0"<< std::endl;
}
this->top = -1;
stack_pointer = new S[this->size_];
};
Stack(const stack& S): size_(S.size_), top_(S.top_){
if(this == &S){
return *this;
}
stack_pointer = new S[S.size_];
for(int i=0; i< size_; i++){
stack_pointer[i] = S[i];
}
this->top = stack_pointer[S.top_];
delete[] S;
}
~Stack(){
delete[] stack_pointer;
}
private:
int size_;
int top_;
S* stack_pointer;
};
这是cpp
#include "stack.hpp"
template<typename S>
bool Stack<S>::push(const S& data){
if(this->top_ >= size-1)
resize();
stack_pointer[++top_]= data;
}
void Stack<S>::resize(){
temp = new S[this->size];
for(int i=0; i< size_; i++){
temp[i] = stack_pointer[i];
}
delete[] stack_pointer;
size_ = size_*2;
stack_pointer = new stack_pointer[size_];
for(int j=0; j < size_/2; j++){
stack_pointer[i] = temp[i];
}
delete[] temp;
}
bool Stack<S>::pop(){
if(top>0){
return stack_pointer[top--];
}else{
return false;
}
}
bool Stack<S>::peek(){
if(top>0){
top--;
}
}
我的问题是,这是在C ++中进行堆栈实现的最佳方式,还是更有效的方法。此类还需要任何类型的运算符重载吗?