C++中的 vector 只能读取最后一个元素
vector in C++ can only read the last element
我在向量中添加了几个元素,但是当我访问它们时,它们都是最后添加的元素。我无法理解。
这是我的代码:
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_ptr
或unique_ptr
相关文章:
- lower_bound()返回最后一个元素
- 获取向量C++中第一个值和最后一个值的和
- 获取用C/C++打印的最后一个字符串
- 读取最后一行代码算法 - c++ 时出现问题
- 全局变量 多读取器 一个写入器多线程安全?
- UDP 套接字读取最后一个传入字节
- std::getline 读取最后一个字符串两次
- 读取最后一个整数文件C++
- C++如何使用读取进程内存查找进程内存中使用的最后一个(偏移量 - 地址)
- C++ 输出在读取文本文件时跳过最后一个单词
- C++中的 vector 只能读取最后一个元素
- c++从ifstream中读取一行的最后一个变量
- Fstream不会保存文件中的最后一个单词,也不会从文件中读取
- C ++ .eof.未读取文件的最后一个值
- 如何从最后一个光标位置读取文件
- 读取文本文件并在C/C++中每行只得到最后一个整数的结果
- gzgetc在读取最后一个字符时设置EOF标志
- 使用SetFilePointerEx读取文件的最后一个簇
- 如何在读取文本文件时跳到每行最后一个数字之后的下一行
- 从使用sstream读取的单词中删除最后一个空格的最佳方法