0

If I have a class's header file like the following:

class arrayStack
{
    private:
        struct StackNode
    {
    StackNode(int p, int v):previous(p),value(v){}
    ~StackNode(){std::cout<<"destructor calledn"<<std::endl;}
    int previous;
    int value;
    };

    public:
    static const int STACKSIZE=100;
    static const int NUMSTACK=3;
    static int indexUsed;
    arrayStack();
    ~arrayStack();
        void push(int stackNum, int val);
    int top(int stackNum);
    void pop(int stackNum);
    bool isEmpty(int stackNum);
    vector<StackNode*> buffer;
        int stackPointer[NUMSTACK];
};

Here is the content of cpp file:

  void arrayStack::push(int stackNum, int val)
  {
int lastIdx=stackPointer[stackNum];
stackPointer[stackNum]=indexUsed;
indexUsed++;
buffer[stackPointer[stackNum]]=new StackNode(lastIdx,val);
  }

  int arrayStack::top(int stackNum)
  {
return buffer[stackPointer[stackNum]]->value;
  }

basically, I know that I need to store STACKSIZE*NUMSTACK StackNode* in the vector buffer (I know I just use an array here). Now, I wonder how I could reserve large enough space for buffer in the ctor.

Here is what I tried:

    buffer.reserve(STACKSIZE*NUMSTACK*sizeof(StackNode*))

but it seems not working, because in the client code, when I tried:

    arrayStack tStack;

for(int i=0;i<3;i++)
    for(int j=0; j<10;j++)
    {
        tStack.push(i,i+j);
    }

the program crashed due to vector assignment over subscript.

user268451
  • 759
  • 2
  • 8
  • 16
  • 2
    What's `push` ? Also, reserve takes the number of elements, not the memory amount in bytes, so you're reserving too much. – R. Martinho Fernandes Sep 27 '11 at 06:24
  • Why do you need to store pointers in a std::vector? note that, reserving memory for a container doesn't mean you're constructing that number of elements, it's only a pre-allocated memory. – cpx Sep 27 '11 at 07:02

1 Answers1

2

It sounds like want to use the resize function, rather than reserve.

Also, as mentioned in a comment, the argument to the function is the number of elements, not the number of bytes.

If you call buffer.resize(23), it will give you a vector of 23 null pointers, which you can then read/modify using square brackets.

exclipy
  • 1,423
  • 1
  • 15
  • 21