繁体   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