简体   繁体   中英

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.

You can use the vector functions

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

more information http://www.cplusplus.com/reference/vector/vector/back/

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;
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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