Karan Singh
Karan Singh

Reputation: 1174

Unable to access vector value by index

#include<iostream>
#include<vector>

using namespace std;

class Stack
{
    public:
        int top;
        vector<int> v;
        Stack(int size)
        {
            top=0;
            cout<<"Enter the values"<<endl;
            for(int i=0; i<size; i++)
            {
                int val;
                cin>>val;
                v.push_back(val);
                top++;
            }
        }
        void push(int val)
        {
            v.push_back(val);
            top++;
        }
        int pop()
        {
            int x=v[top];
            top--;
            return x;
        }
        void disp()
        {
            for(int j=top; j<=0; j--)
                cout<<v[j]<<' ';
        }
};

int main()
{
    Stack s(3);
    int k=s.pop();
    cout<<k;
    return 0;
}

I am trying to learn the basics of OOP.

Here, my Stack constructor and push function are working fine, but there is a problem with the pop and disp functions. I'm assuming that I am using an incorrect syntax to access the elements of a vector(maybe?). Can anyone tell me where I am going wrong?

Also, the value of k always comes out to be 0.

Upvotes: 0

Views: 946

Answers (3)

Austin Yates
Austin Yates

Reputation: 108

As some of the other answers say, you can use the built-in vector functions to do these things (see pop_back and back.

However, if you want to define your own, I would use the vector.at(index) function. Addressing the values with the index as you have works, but it doesn't do any bounds checking at() does. Which would solve your problem above where your index isn't correct for the zero-based indexing of a vector.

Upvotes: 1

user7177818
user7177818

Reputation:

You can use the vector functions

int k = s.back();
s.pop_back();
cout << k;

more informationhttp://www.cplusplus.com/reference/vector/vector/back/

Upvotes: 2

R Sahu
R Sahu

Reputation: 206717

You have a off-by-one index error.

The way you have implemented your class, when there are N items in the stack, the value of top is N.

Hence, top is not a valid index to access the elements of v. You can use:

int pop()
{
    int x=v[top-1];
    top--;
    return x;
}

or

int pop()
{
    top--;
    int x=v[top];
    return x;
}

Upvotes: 1

Related Questions