2016-11-28 40 views
-3

我向矢量添加了幾個元素,但是當我訪問它們時,它們都是最後添加的元素。我無法理解。C++中的矢量只能讀取最後一個元素

這裏是我的代碼:

while(true){ 
    cin>>shape; 
    if(shape=='X') break; 
    if(shape=='C'){ 
     cin>>x>>y>>r; 
     Circle c(x,y,r); 
     shapes[sum] = &c; 
     //cout<<shapes[sum]->getArea()<<endl; 
     sum++; 
    }else if(shape=='R'){ 
     cin>>x1>>y1>>x2>>y2; 
     Rectangle rec(x1,y1,x2,y2); 
     shapes[sum] = &rec; 
     //cout<<shapes[sum]->getArea()<<endl; 
     sum++; 
    } else if(shape=='T'){ 
     cin>>x1>>y1>>x2>>y2>>x3>>y3; 
     Triangle tr(x1,y1,x2,y2,x3,y3); 
     shapes[sum] = &tr; 
     //cout<<shapes[sum]->getArea()<<endl; 
     sum++; 
    } 
} 
for(int j=0; j<sum; j++){ 
    showArea(shapes[j]); 
} 

我發現,在最後,在矢量的所有元素是一樣的,它們是在最後添加的元素。

+3

後的[MCVE]請,如果你想有一個簡潔的答案,而不是猜測。 –

+5

我懷疑你的矢量存儲指針。而且,您存儲局部變量的指針=> UB – Garf365

+2

此外,除非矢量的大小從一開始就設置,否則'shapes [']可能超出範圍。另一個未定義行爲的案例。 –

回答

3

你的矢量存儲指針。你存儲在它裏面的局部變量的指針:

} else if(shape=='T'){ 
    cin>>x1>>y1>>x2>>y2>>x3>>y3; 
    Triangle tr(x1,y1,x2,y2,x3,y3); // <= Create local variable, automatic allocation 
    shapes[sum] = &tr; // <= store its address 
    //cout<<shapes[sum]->getArea()<<endl; 
    sum++; 
} // <= automatic dealocation of tr, ie tr doesn't exist anymore 
    // shapes[sum - 1] stores address of no more existing variable => Undefined behavior 

你應該做的:

} else if(shape=='T'){ 
    cin>>x1>>y1>>x2>>y2>>x3>>y3; 
    Triangle *tr = new Triangle(x1,y1,x2,y2,x3,y3); // manual allocation 
    shapes.push_back(tr); 
    //cout<<shapes[sum]->getArea()<<endl; 
    sum++; 
} 

必須收回與delete當你不再需要在矢量

對象

sum沒有必要:您必須使用push_back以避免未定義的行爲,之後,您可以使用shapes.size()來檢索矢量的大小。

事實上,訪問到向量的元素是選自界(當你vector[n]n是等於或大於vector.size()更大)是未定義的行爲。這樣做的


現代的方法:使用shared_ptrunique_ptr

+0

那麼該如何解決呢? – laoqiren

+0

但此示例有效:#include #include #include using namespace std; () int vector k; int * p = new int [15]; (int j = 0; j <15; j ++) { p [j] = j; k.push_back(&p[j]); } 對(INT I = 0; I <15;我++){ COUT << * K [I] <<「 」;} 刪除 []磷; 系統(「暫停「); return 0; } – laoqiren

+0

非常感謝,你們幫了我很多。 – laoqiren