Vector.erase(Iterator) 导致内存访问错误
我正在尝试对存储在 vector
中的 videoObjects
进行 Z 索引重新排序。计划是识别要放置在矢量第一个位置的视频对象,将其删除,然后将其插入到第一个位置。不幸的是,erase()
函数总是会导致错误的内存访问。
这是我的代码:
testApp.h:
vector<videoObject> videoObjects;
vector<videoObject>::iterator itVid;
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);
}
}
这应该很简单,但我只是不知道我在哪里走错了路。
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.
Here is my code:
testApp.h:
vector<videoObject> videoObjects;
vector<videoObject>::iterator itVid;
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您应该
引用 cplusplus.com :
更新:您访问条件中当前元素的方式看起来相当奇怪。此外,还必须避免在擦除后递增迭代器,因为这会跳过一个元素并可能导致越界错误。试试这个:
You should do
Quote from cplusplus.com:
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:请注意,从向量中一一删除元素具有二次复杂度。 STL 来救援!
Beware, erasing elements one by one from a vector has quadratic complexity. STL to the rescue!
迭代列表时无法删除,因为迭代器无效。您应该使用 Erase 的返回迭代器将其设置为当前迭代器。
You cannot delete while iterating over the list because the iterator gets invalid. You should use the return iterator of Erase to set it to your current iterator.
erase
函数返回下一个有效的迭代器。您必须创建一个 while 循环并执行类似
相应检查的操作。
erase
function returns the next valid iterator.You would have to make a
while
loop and do something likewith corresponding checks.