vector ::用指针成员擦除 [英] vector::erase with pointer member

查看:164
本文介绍了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 {visibleShape = 0; shapeNum = -1;};

//复制构造函数以支持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,一切都按预期工作:visibleShape指向的数据是使用复制构造函数复制的。



但是当我使用vector :: erase去掉Hyp从向量,其他元素正确移动除了指针成员visibleShape,现在指向错误的地址!如何避免这个问题?

我想你缺少一个重载的赋值运算符 Hyp

code>。


I am manipulating vectors of objects defined as follow:

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

};

When I create a Hyp object, allocate/write memory to visibleShape and add the object to a vector with vector::push_back, everything works as expected: the data pointed by visibleShape is copied using the copy-constructor.

But when I use vector::erase to remove a Hyp from the vector, the other elements are moved correctly EXCEPT the pointer members visibleShape that are now pointing to wrong addresses! How to avoid this problem? Am I missing something?

解决方案

I think you're missing an overloaded assignment operator for Hyp.

这篇关于vector ::用指针成员擦除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆