c++ - 如果超过我的堆栈大小,我如何自动调整它? C++

标签 c++ automation stack stack-overflow stack-size

所以我有一个使用 LIFO(后进先出)方法的 CStack 类。使用标准变量 bottom/top/size 和方法,例如 push/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_;
    }
};

最佳答案

这应该做你想做的。它不处理异常,但我想您的类(class)还没有走那么远吗?

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_++;
}

关于c++ - 如果超过我的堆栈大小,我如何自动调整它? C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23748456/

相关文章:

assembly - 有什么可以防止汇编中的堆栈溢出吗?

c++ - vector 下标超出范围错误 C++

c++ - 在字符串迭代中替换(out_of_range)

windows - Ansible Delegate_to WinRM

tree - 如何在 Rust 中实现可变的仙人掌堆栈?

c++ - 回文函数(字符串、堆栈、队列)

c++ - setbuf 什么时候有用(除了 NULL 值)?

c++ - 如何取回长整数的两个分量

.net - 自动化测试工具

api - 使用VBScript控制记事本