【发布时间】:2019-02-03 06:13:01
【问题描述】:
我正在使用数组构建一个堆栈(我的老师不会让我使用标准容器),我被卡住了。即使我重新定义了访问运算符[],当我推送时,程序突然停止了。 (我实现了复制构造函数 operator = 和销毁器 bur,为了便于阅读,我省略了这些方法)。
template <typename T>
class stack{
private:
unsigned int _capacity; //capacità massima
unsigned int _size; //dimensione attuale
T* _stack;
public:
stack()
: _capacity(10), _size(0), _stack(0){}
T& operator[](unsigned int _index)
{
assert(_index < _size);
return _stack[_index];
}
void push (const T &value){
if (_size == _capacity){ //double the stack dimension
if(_capacity==0)
_capacity=10;
_capacity *= 2;
T* tmp = new T[_capacity];
copy_n(_stack, _size, tmp);
swap(_stack, tmp);
delete[] tmp;
}
_stack[_size] = value;
++_size;
}
void print(){
for(unsigned int i = 0; i < _size; ++i)
cout << _stack[i] << " ";
cout << endl;
}
我的主线很简单:
int main(){
stack<int> s;
s.push(2);
s.print();
return 0;
}
【问题讨论】:
-
_capacity(10), _size(0), _stack(0),和stack == nullptr,capacity怎么可以是10? -
if (_size == _capacity)对于新创建的stack永远不会为真,因为_capacity是10和_size是0。因此,您永远不会为_stack分配数组 -
stack不应该有operator[]。它是一个 FIFO 数据结构,唯一可用的应该是“顶部”,您可以push和pop它。 -
@NathanOliver 我很清楚, [ ] 是执行推送操作,因为我用数组实现它,否则是不可能的
-
@man_o_war 你的
push函数帮你推送。您不需要定义operator[]来帮助解决这个问题。_stack[_size] = value;不使用您的operator[],而是使用为指针定义的operator[]。
标签: c++ arrays stack operators