how to reserve vector space for class objects? [duplicate]
If I have a class's header file like the following:
class arrayStack
{
private:
struct StackNod开发者_StackOverflow中文版e
{
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.
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.
精彩评论