簡體   English   中英

在C ++中使用向量實現堆棧

[英]Implementation of stack using vectors in c++

#include<iostream>
#include<vector>
using namespace std;
class Stack {

private:
    int maxSize;
    vector<int> v;
    int top;
public:
    Stack(int size) {
        this->maxSize = size;
        this->v.reserve(this->maxSize);
        this->top = -1;
    }

    void push(int j) {
        if (!(this->isFull())) {
            this->v[++this->top] = j;
        } else {
            cout << "stack is full"<<endl;
        }

    }

    int pop() {
        if (!(this->isEmpty())) {

            return this->v[this->top--];
        } else {
            cout << "\nstack is empty"<<endl;
            cout<<  "StackOverflow "<<endl;
        }
    }

    int peak() {
        return this->v[this->top];
    }
    bool isEmpty() {
        return (this->top == -1);
    }

    bool isFull() {
        return (this->top == this->maxSize - 1);
    }

};

int main() {

    Stack s(10);

    s.push(10);
    s.push(20);
    cout<<s.pop();
    cout<<"\n"<<s.pop();
    s.push(40);
    cout<<"\n"<<s.pop();

}

由於以下原因,如何使此代碼更好,更可靠:

  • 該代碼的輸出為20 10 40。

  • 但是在輸出中,我想在每次從堆棧中彈出所有元素后堆棧為空后打印“堆棧為空”

  • 每次都無法打印“ Stackis Empty”

您的代碼中包含UB:

this->v[++this->top] = j;

 return this->v[this->top--];    

等等。 您在std::vector中保留空間的事實並不使訪問thous元素合法,而是您無法訪問元素。 而且您使代碼過於復雜std::vector保持其大小,因此根本不需要索引top 您需要做的就是push_back()添加元素,然后使用back()訪問最后一個元素,然后使用pop_back()刪除它。 您可以使用std::vector>::empty()std::vector::size()來檢查是否還有元素。

代碼中的特定問題是由於您嘗試使用std::vector進行越界訪問; 其行為是不確定的 請注意, reserve並未使該數量的元素可供使用; 僅在沒有后續內存重新分配的情況下才可能可用。 如果你曾經使用at ,而不是[]那么你的C ++標准庫將拋出一個運行時錯誤。

std::vector具有push_backpop_back函數,可讓您使用它合理有效地對堆棧建模。

但是typedef std::stack<int> Stack; 到目前為止,代替所有代碼是最好的方法。

不要使用C ++標准庫容器對象為C ++標准庫中的其他容器建模。 容器對象確實很難正確編寫。 並進行大量調試。

按照您編程的方式,如果在調用pop時堆棧已為空,則僅顯示“堆棧為空”,而在堆棧具有1個元素且僅在調用pop之后為空時,則僅顯示“堆棧為空”。

假設您在堆棧上有1個元素。 所以top是0。

int pop() {
    if (!(this->isEmpty())) {

if為true,則不會打印任何內容。 這是因為isEmpty()計算結果為falsetop設置為0。

您要做的是先彈出, 然后檢查堆棧是否為空。 無論哪種方式,一開始都要檢查它,因為您無法彈出空堆棧。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM