Vector out of range

Started by
6 comments, last by Medo Mex 10 years, 12 months ago

I'm rendering billboards using map:


<LPDIRECT3DTEXTURE9, vector<DWORD>*> mapTexture;

I'm iterating through the map to render billboards with the same texture so I can draw multiple billboard using the same texture with one draw call.

When the emitter die, I set m_Dead to true in the emitter class, now I want to remove the dead emitters from the particles manager.

So I use:


void ParticleManager::RemoveEmitter(DWORD EMITTER_ID)
{
    if (emitters.size() > EMITTER_ID)
    {
        vector<DWORD> *CurrentIDS = mapTexture[emitters[EMITTER_ID]->texture];
        if (CurrentIDS != NULL)
        {
             CurrentIDS->erase(std::remove(CurrentIDS->begin(), CurrentIDS->end(), EMITTER_ID), CurrentIDS->end());
             mapTexture[emitters[EMITTER_ID]->texture] = CurrentIDS;
        }

        emitters.erase(emitters.begin() + EMITTER_ID);
        }
}

I'm getting out of range exception.

Advertisement
if (emitters.size() > EMITTER_ID)
You should use < instead of > on this line.

If I did that, the emitters will never get removed.

My fault. I got confused because of the upper case and I'm not used to having the comparison in that order.

You could use a debugger and print the stack trace to see where the error takes place. That's probably the easiest way.

This line is not necessary.
mapTexture[emitters[EMITTER_ID]->texture] = CurrentIDS;

If I changed this line:


CurrentIDS->erase(std::remove(CurrentIDS->begin(), CurrentIDS->end(), EMITTER_ID), CurrentIDS->end());

To:


CurrentIDS.clear();

I don't get out of range exception, but of course that will be a problem because I will be removing all the emitters, instead of the one that I want.

Erase invalidates all iterators if i recall correctly.

When you erase an emitter all emitters stored after it in the vector will now be stored at another index (-1), so the indices that you store in the vectors will no longer be correct.

Yes, I figured out that myself and resolved the problem :)

I had to use a pointer to the emitter instead of the emitter Id.

Thank you,

This topic is closed to new replies.

Advertisement