gpt4 book ai didi

c++ - vector::erase with pointer 成员

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:06:06 24 4
gpt4 key购买 nike

我正在操纵定义如下的对象 vector :

class Hyp{
public:
int x;
int y;
double wFactor;
double hFactor;
char shapeNum;
double* visibleShape;
int xmin, xmax, ymin, ymax;

Hyp(int xx, int yy, double ww, double hh, char s): x(xx), y(yy), wFactor(ww), hFactor(hh), shapeNum(s) {visibleShape=0;shapeNum=-1;};

//Copy constructor necessary for support of vector::push_back() with visibleShape
Hyp(const Hyp &other)
{
x = other.x;
y = other.y;
wFactor = other.wFactor;
hFactor = other.hFactor;
shapeNum = other.shapeNum;
xmin = other.xmin;
xmax = other.xmax;
ymin = other.ymin;
ymax = other.ymax;
int visShapeSize = (xmax-xmin+1)*(ymax-ymin+1);
visibleShape = new double[visShapeSize];
for (int ind=0; ind<visShapeSize; ind++)
{
visibleShape[ind] = other.visibleShape[ind];
}
};

~Hyp(){delete[] visibleShape;};

};

当我创建一个 Hyp 对象、分配/写入内存给 visibleShape 并使用 vector::push_back 将该对象添加到一个 vector 时,一切都按预期工作:visibleShape 指向的数据是使用复制构造函数复制的。

但是当我使用 vector::erase 从 vector 中删除一个 Hyp 时,除了现在指向错误地址的指针成员 visibleShape 之外,其他元素都被正确移动了!如何避免这个问题?我错过了什么吗?

最佳答案

我认为您缺少 Hyp 的重载赋值运算符。

关于c++ - vector::erase with pointer 成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2677770/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com