Vector.erase(Iterator) causes bad memory access(Vector.erase(Iterator) 导致内存访问错误)
问题描述
我正在尝试对存储在 vector 中的 videoObjects 进行 Z-Index 重新排序.计划是识别将要放在 vector 的第一个位置的 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:
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.
推荐答案
你应该做的
itVid = videoObjects.erase(itVid);
引用自 cplusplus.com:
[vector::erase] 使所有迭代器和对 position 或 first 之后元素的引用无效.
[
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) 导致内存访问错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Vector.erase(Iterator) 导致内存访问错误
基础教程推荐
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- CString 到 char* 2021-01-01
