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

标签 c++ stl vector pointers erase

我正在操纵定义如下的对象 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/

相关文章:

引用类型的 C++11 成员变量, vector push_back 后的不同行为

c++ - 寻找具有下限的最近点......但数据未排序

c++ - 为什么我们需要使用 folly::fbvector 而不是 std::vector 和最初保留大的未提交区域的分配器?

c++ - 逐步将 gcov 与 CMake 结合使用

c++ - 为什么缓冲区获得垃圾值?

c# - 在与 STL 混合的 C# 中调用非托管 C++ 代码

c++ - 返回指向 vector 数据的指针的最佳方法是什么? const 还是非常量?

c++ - 为什么sub_match和basic_string比较运算符使用额外的字符串拷贝来实现?

c++ - 在 MFC 中禁用快捷键表项

c++ - 如何用 STL 实现替换这个 for 循环?