我有一个具有向量v_group的Group类; 和ofc得到矢量大小和删除项目的东西:
小组课程
void Group::drawGroup()
{
for(int i = 0; i < v_group.size(); i++)
{
v_group.at(i).draw();
}
}
void Group::add(Mesh object)
{
v_group.push_back(object);
}
Mesh &Group::get(int location)
{
return v_group.at(location);
}
void Group::clear()
{
v_group.clear();
}
void Group::remove(int location)
{
v_group.erase(v_group.begin()+(location));
}
bool Group::remove(Mesh object)
{
return true;
}
int Group::size()
{
return v_group.size();
}
在我的另一个课程中,我正在创建一个Group对象:
in header: `Group *m_group;`
Renderer::Renderer() : m_group(new Group())
{
}
void Renderer::drawGL()
{
m_group->drawGroup();
}
void Renderer::addObject(float width,float height,string texture_url)
{
UseableObject uobj(width,height,texture_url);
m_group->add(uobj);
}
void Renderer::RemoveObject(int index)
{
m_group->remove(index);
}
void Renderer::move(int objectIndex, float x, float y)
{
m_group->get(objectIndex).setPosX(x);
m_group->get(objectIndex).setPosY(y);
}
Group& Renderer::GetGroup()
{
return *m_group;
}
在其他地方我想要使用以下方法从初始Group向量中删除对象:
DropObject::DropObject(Renderer *renderer)
{
this->renderer = renderer;
//insert a i (count) into the vector to represent the already Available objects, and continue from there with the DropObjects
for(int i = 0;i < renderer->getGroupSize();i++)
{
yIndex.push_back(10); //Vector
xIndex.push_back(10); //Vector
}
}
DropObject::~DropObject()
{
}
void DropObject::Create(int &ENEMY_movePosition, const int &ENEMY_start_height)
{
renderer->addObject(20,20,"");
xIndex.push_back(ENEMY_movePosition);
yIndex.push_back(ENEMY_start_height);//just add index, nothing else cam into my mind right now ._.
cout << ENEMY_start_height << endl;
for(int i = 0; i < yIndex.size();i++)
{
cout << "y vec= " << yIndex[i] << endl;
}
}
void DropObject::Move(int index)
{
//current index set to isRemoved = false , because it's still there
isRemoved = false;
//x remains the same, y decrease by 1 (-> =-1)
try
{
yIndex[index] -= 2;
renderer->move(index,xIndex[index],yIndex[index]);
if(yIndex[index] < -250)
{
//renderer->RemoveObject(index);
renderer->GetGroup().remove(index);
yIndex.erase(yIndex.begin() + index);
xIndex.erase(yIndex.begin() + index);
isRemoved = true;
}
}catch(std::out_of_range ex)
{
cout << "DropObject move out of range:" << ex.what() << endl;
}
}
有效,但在xIndex.erase(yIndex.begin() + index);
之后,程序崩溃并出现分段错误
或者当我试图再次从Group调用向量时。我得到一个malloc():内存损坏(快速)错误。
也许在擦除一个元素之后,仍然会为它分配内存,因此我会出现这样的错误?
任何人都可以提供帮助吗?
答案 0 :(得分:0)
yIndex.erase(yIndex.begin() + index);
xIndex.erase(yIndex.begin() + index);
at xIndex.erase()我使用了yIndex而不是xIndex。 可怕的错误。