简体   繁体   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();

}

How can I make this code more better and reliable for these reasons: 由于以下原因,如何使此代码更好,更可靠:

  • The output of this code is 20 10 40 . 该代码的输出为20 10 40。

  • But in the output I want to print "Stack is empty" after every time the stack is empty after popping out all the elements from the stack 但是在输出中,我想在每次从堆栈中弹出所有元素后堆栈为空后打印“堆栈为空”

  • It fails toprint "Stackis Empty " every time . 每次都无法打印“ Stackis Empty”

You have UB in your code: 您的代码中包含UB:

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

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

ans so on. 等等。 The fact that you reserved space in a std::vector does not make accessing thous elements legal, you access elements out of bounds. 您在std::vector中保留空间的事实并不使访问thous元素合法,而是您无法访问元素。 And you overcomplicated your code - std::vector maintains it's size so you do not need index top at all. 而且您使代码过于复杂std::vector保持其大小,因此根本不需要索引top All you need is push_back() adding element and use back() to access last and then pop_back() to remove it. 您需要做的就是push_back()添加元素,然后使用back()访问最后一个元素,然后使用pop_back()删除它。 You can use std::vector>::empty() or std::vector::size() to check if there are elements left. 您可以使用std::vector>::empty()std::vector::size()来检查是否还有元素。

The specific problem in your code is due to your attempting out of bounds access with a std::vector ; 代码中的特定问题是由于您尝试使用std::vector进行越界访问; the behaviour of which is undefined . 其行为是不确定的 Note that reserve does not make that number of elements available for use; 请注意, reserve并未使该数量的元素可供使用; only potentially available without a subsequent memory reallocation. 仅在没有后续内存重新分配的情况下才可能可用。 If you had used at rather than [] then your C++ standard library would have thrown a runtime error. 如果你曾经使用at ,而不是[]那么你的C ++标准库将抛出一个运行时错误。

std::vector has push_back and a pop_back functions which does allow you to use it to model a stack reasonably effectively. std::vector具有push_backpop_back函数,可让您使用它合理有效地对堆栈建模。

But , typedef std::stack<int> Stack; 但是typedef std::stack<int> Stack; in place of all your code is by far the best way. 到目前为止,代替所有代码是最好的方法。

Don't use C++ standard library container objects to model other containers that are also in the C++ standard library. 不要使用C ++标准库容器对象为C ++标准库中的其他容器建模。 Container objects are really difficult to write properly; 容器对象确实很难正确编写。 and take a lot of debugging. 并进行大量调试。

The way you programmed it, it only prints "Stack is empty" if the stack is already empty when you call pop , not when it has 1 element and is only empty after calling pop . 按照您编程的方式,如果在调用pop时堆栈已为空,则仅显示“堆栈为空”,而在堆栈具有1个元素且仅在调用pop之后为空时,则仅显示“堆栈为空”。

Suppose you have 1 element on the stack. 假设您在堆栈上有1个元素。 So top is 0. 所以top是0。

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

This if evaluatetes to true, and therefore nothing will be printed. if为true,则不会打印任何内容。 This is because isEmpty() evaluates to false with top set to 0. 这是因为isEmpty()计算结果为falsetop设置为0。

What you want to do is doing the pop first, and then checking if the stack is empty. 您要做的是先弹出, 然后检查堆栈是否为空。 On top of checking it at the beginning either way, because you can't pop an empty stack. 无论哪种方式,一开始都要检查它,因为您无法弹出空堆栈。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM