C++中的 vector 只能读取最后一个元素

vector in C++ can only read the last element

本文关键字:读取 最后一个 元素 中的 vector C++      更新时间:2023-10-16

我在向量中添加了几个元素,但是当我访问它们时,它们都是最后添加的元素。我无法理解。

这是我的代码:

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

我发现最后,向量中的所有元素都是相同的,它们是最后添加的元素。

您的向量存储指针。您将局部变量的指针存储在其中:

} 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