C ++:std :: copy失败,访问冲突读取位置错误

时间:2015-12-20 15:26:23

标签: c++ list copy

我尝试使用 std :: copy C ++函数复制我创建的类中的对象列表,但该函数崩溃并显示下一条错误消息:

  

0x00007FFA91BAC570(msvcr120.dll)中的未处理异常   MyProject.exe:0xC0000005:访问冲突读取位置   0xFFFFFFFFFFFFFFFF。

该类非常简单,我不知道是什么原因导致复制功能因此类错误而崩溃。 该课程如下:

class XMLObjects
    {
    private:
        int id;
        string name;
        int leftUpCornerX;
        int leftUpCornerY;
        int rightDownCornerX;
        int rightDownCornerY;
        bool isFound; //it's true if this object was found in the OR file and in the GT file

public:
    XMLObjects(){}
    XMLObjects(int _id){ id = _id; }
    XMLObjects(int _id, string _name, int _leftUpCornerX, int _leftUpCornerY, int _rightDownCornerX, int _rightDownCornerY) { id = _id; name = _name; leftUpCornerX = _leftUpCornerX; leftUpCornerY = _leftUpCornerY; rightDownCornerX = _rightDownCornerX; rightDownCornerY = _rightDownCornerY; isFound = false; }
    ~XMLObjects(){}

    void setID(int _id){ id = _id; }
    void setName( string _name){ name=_name; }
    void setLeftUpCorner(int _leftUpCornerX, int _leftUpCornerY){ leftUpCornerX = _leftUpCornerX; leftUpCornerY = _leftUpCornerY; }
    void setRightDownCorner(int _rightDownCornerX, int _rightDownCornerY){ rightDownCornerX = _rightDownCornerX; rightDownCornerY = _rightDownCornerY; }
    void objectWasFound(){ isFound = true; }

    int getID(){ return id; }
    string getName(){ return name; }
    int getLeftUpCornerX(){ return leftUpCornerX; }
    int getLeftUpCornerY(){ return leftUpCornerY; }
    int getRightDownCornerX(){ return rightDownCornerX; }
    int getRightDownCornerY(){ return rightDownCornerY; }
    bool isObjectFound(){ return isFound; }
};

对复制功能的调用如下所示:

list<XMLObjects> objects;
objects.push_front(obj1);
objects.push_front(obj2);
objects.push_front(obj3);
list<XMLObjects> NewObjectsList;
std::copy(objects.begin(), objects.end(), NewObjectsList.begin());

有人可以帮忙吗?

1 个答案:

答案 0 :(得分:4)

std::copy不会调整输出大小,因此您必须先调整容器大小,或使用插入元素的特殊迭代器。

您可以使用以下代码。

std::copy(objects.begin(), objects.end(),
          std::inserter(NewObjectsList, NewObjectsList.end()));

如评论中所述,在您的情况下,您可以直接复印一份:

list<XMLObjects> NewObjectsList = objects;