【问题标题】:Accessing a template stack using operator[]使用 operator[] 访问模板堆栈
【发布时间】: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 == nullptrcapacity怎么可以是10
  • if (_size == _capacity) 对于新创建的stack 永远不会为真,因为_capacity10_size0。因此,您永远不会为 _stack 分配数组
  • stack 不应该有operator[]。它是一个 FIFO 数据结构,唯一可用的应该是“顶部”,您可以 pushpop 它。
  • @NathanOliver 我很清楚, [ ] 是执行推送操作,因为我用数组实现它,否则是不可能的
  • @man_o_war 你的push 函数帮你推送。您不需要定义 operator[] 来帮助解决这个问题。 _stack[_size] = value; 不使用您的operator[],而是使用为指针定义的operator[]

标签: c++ arrays stack operators


【解决方案1】:

当您编写自己的 Stack 类时,请记住这一点。如果要确保实际插入了值,请实现一个 top() 函数,该函数返回 stack[top] 处的值。在每个push() 之后检查top()。 话虽这么说,在您的情况下_stack[_size] = value; 不使用operator[]

【讨论】:

  • 是的,top() 方法已经实现了,但是为了更好的可读性我省略了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-01
  • 2014-09-13
  • 1970-01-01
相关资源
最近更新 更多