如果超出了堆栈的大小,如何自动调整它?c++

If the size of my stack is exceeded, how do I automatically adjust it? C++

本文关键字:何自动 调整 c++ 堆栈 如果      更新时间:2023-10-16

所以我有一个使用LIFO(后进先出)方法的类CStack。使用标准变量bottom/top/sizepush/pop/full/empty/print之类的方法。这是一个char堆栈

我的问题是,如果我添加一些东西到这个堆栈,当它是满的,我怎么能自动调整大小?我想到了memcpy()方法,但我真的不明白它是如何工作的(还)。

任何帮助都将不胜感激。

下面是我的代码:
class CStack {
private:
    char *bottom_;
    char *top_;
    int size_;
public:
    CStack(int n = 20) {
        bottom_ = new char[n];
        top_ = bottom_;
        size_ = n;
    }
    void push(char c) {
        *top_ = c;
        top_++;
    }
    int num_items() {
        return (top_ - bottom_);
    }
    char pop() {
        top_--;
        return *top_;
    }
    int full() {
        return (num_items() >= size_);
    }
    int empty() {
        return (num_items() <= 0);
    }
    void print() {
        cout << "Stack currently holds " << num_items() << " items: ";
        for (char *element = bottom_; element < top_; element++) {
            cout << " " << *element;
        }
        cout << "n";
    }
    ~CStack() { // stacks when exiting functions 
        delete [] bottom_;
    }
};

这应该是您想要的。它不处理异常但我猜你们在课程中还没学到这些?

void push(char c) {
    int used = top - bottom;
    if (used >= size_) {
        // grow the stack
        char* newBottom = new char[used + 20];
        memcpy(newBottom, bottom_, used * sizeof(char));
        top_ = newBottom + used;
        size_ = used + 20;
        delete[] bottom_;
        bottom_ = newBottom;        
    }
    *top_ = c;
    top_++;
}