Vector.erase(Iterator)导致内存访问不良 [英] Vector.erase(Iterator) causes bad memory access
问题描述
我试图对存储在向量
中的 videoObjects
执行Z索引重新排序。该计划是确定要放在向量
的第一个位置的 videoObject
,将其擦除然后将其插入第一个位置。不幸的是, erase()
函数总是导致不良内存访问。
I am trying to do a Z-Index reordering of videoObjects
stored in a vector
. The plan is to identify the videoObject
which is going to be put on the first position of the vector
, erase it and then insert it at the first position. Unfortunately the erase()
function always causes bad memory access.
以下是我的代码:
testApp.h:
testApp.h:
vector<videoObject> videoObjects;
vector<videoObject>::iterator itVid;
testApp.cpp:
testApp.cpp:
// Get the videoObject which relates to the user event
for(itVid = videoObjects.begin(); itVid != videoObjects.end(); ++itVid){
if(videoObjects.at(itVid - videoObjects.begin()).isInside(ofPoint(tcur.getX(), tcur.getY()))){
videoObjects.erase(itVid);
}
}
这应该这么简单,看到我错了转弯。
This should be so simple but I just don't see where I'm taking the wrong turn.
Thx,
xonic
Thx, xonic
推荐答案
您应该这样做
itVid = videoObjects.erase(itVid);
[
vector :: erase
]无效所有迭代器并引用之后 的元素。
[
vector::erase
] invalidates all iterator and references to elements after position or first.
返回值:迭代器指向在被函数调用擦除的最后一个元素之后的元素的新位置,如果操作擦除序列中的最后一个元素,则该向量是向量结尾。
Return value: A random access iterator pointing to the new location of the element that followed the last element erased by the function call, which is the vector end if the operation erased the last element in the sequence.
更新:,访问您的条件中当前元素的方式看起来很奇怪。还必须避免在 erase
之后递增迭代器,因为这会跳过一个元素,并可能导致超出边界的错误。尝试:
Update: the way you access the current element inside your condition looks rather strange. Also one must avoid incrementing the iterator after erase
, as this would skip an element and may cause out-of-bounds errors. Try this:
for(itVid = videoObjects.begin(); itVid != videoObjects.end(); ){
if(itVid->isInside(ofPoint(tcur.getX(), tcur.getY()))){
itVid = videoObjects.erase(itVid);
} else {
++itVid;
}
}
这篇关于Vector.erase(Iterator)导致内存访问不良的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!