-3

I am trying to make a simple application based on stack and my code is giving an error when I am trying to run it. The code is here:

// Stacks.cpp : Defines the entry point for the console application.
    //

    #include "stdafx.h"
    #include<iostream>
    #include<vector>
    using namespace std;

    class stackx{
    private:
        int top;
        vector<double> stackVect;
        int maxSize;

public:
    stackx(int s): maxSize(s),top(-1){
        stackVect.reserve(maxSize);
    }

    void push(double a){
        stackVect[++top]=a;
    }

    double pop(){
        return stackVect[top--];
    }

    double peek(){
        return stackVect[top];
    }

    bool isEmpty(){
        return (top==-1);
    }

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

};


int main(){

    stackx stackvect(6);
    stackvect.push(20);
    stackvect.push(22);
    stackvect.push(13);
    stackvect.push(69);
    stackvect.push(123);

    while(!stackvect.isEmpty()){
        double value = stackvect.pop();
        cout<<value<<" ";
    }
    cout<<endl;
    return 0;
}

Where am I making the mistake ?

Ashraf Bashir
  • 9,686
  • 15
  • 57
  • 82
shashankgaurav
  • 65
  • 1
  • 1
  • 9

2 Answers2

0

I guess you're not using correctly std::vector.

You should use push_back instead of stackVect[++p], pop_back instead of stackvect[p--] and back for peek.

As for the answer to why, it's simply because the vector is empty/not of size "top", and accessing a value won't work. stackVect[10000] does not create up to 10000 items, simply access it. If it does not exists, result is unpredictable.

And in that case, you should use at which does the same, but throws an exception upon invalid offset.

NoDataFound
  • 11,381
  • 33
  • 59
0

Vectors do not resize automatically when you access them with [], so the code

stackVect[++top]=a;

which you expected to add an element to the vector is out-of-bounds access. You need to use methods like push_back to add elements to vectors. However, in your code top is not needed at all. Use the size of the vector instead. So e.g. isEmpty would be defined as

return stackVect.empty();

Then push_back, pop_back, and back methods of the vector is all you need. Or even better, use std::stack, which has all of it builtin (in slightly different, exception-safe way to implement pop).

Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51