无法按索引访问矢量值

时间:2017-08-18 19:57:19

标签: c++

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

我正在努力学习OOP的基础知识。

这里,我的Stack构造函数和push函数工作正常,但是pop和disp函数存在问题。 我假设我使用不正确的语法来访问向量的元素(可能?)。谁能告诉我哪里出错了?

此外,k的值总是为0。

3 个答案:

答案 0 :(得分:2)

您可以使用矢量函数

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

更多信息http://www.cplusplus.com/reference/vector/vector/back/

答案 1 :(得分:1)

你有一个一个一个索引错误。

您实施课程的方式,当堆栈中有N个项目时,top的值为N

因此,top不是访问v元素的有效索引。您可以使用:

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

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

答案 2 :(得分:1)

正如其他一些答案所说,您可以使用内置的向量函数来执行这些操作(请参阅pop_backback

但是,如果你想定义自己的,我会使用vector.at(index)函数。您可以使用索引处理值,但它不会执行任何边界检查at()。哪个可以解决上面的问题,你的索引对于向量的从零开始的索引不正确。

相关问题