0

したがって、LIFO(Last in First out) メソッドを使用するクラス 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_;
    }
};
4

1 に答える 1

2

これはあなたが望むことをするはずです。それは例外を処理しませんが、あなたのコースはまだそこまで進んでいないと思いますか?

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_++;
}
于 2014-05-20T00:38:05.423 に答える