0
#include<iostream>
#include<vector>
using namespace std;
class t{
    public:
        t();
        void updateSize();
        int getSize();
        void insert();
        int get(int a);
    private:
        int size;
        vector<int> v;

};

t::t(){
    size =0;
}
void t::updateSize(){
    size++;
}
int t::getSize(){
    return size;
}
int t::get(int a){
    return v[a];
}
 void t::insert(){
    v.push_back(size);

    ++size;
}

int main(){
   t xa;
   xa.insert();
   xa.insert();
   xa.insert();
       xa.insert();
   cout<<xa.get(3);//expect to output 3 but instead outputs 0


   return 0;
}

这段代码应该在我每次调用 insert 时增加大小,并将具有该大小值的整数放入该大小的相同索引处的向量中。但由于某种原因,它没有将更新后的大小放入我的向量中。

4

2 回答 2

4

您正在插入 3 个元素,但您正在阅读第 4 个元素(因为索引是基于 0 的)。

于 2012-12-06T07:07:01.077 回答
0

您发布的程序将打印“3”。证明阅读您的代码。

于 2012-12-06T07:15:27.003 回答