3

I am fairly new to c++, but had a question about vectors. My goal is to remove an element from the vector using erase once I hit my out of bounds condition. This all seems to work fine, except that when I call erase, it will be pointing to the first element, but delete the last. Basically, the loop will continue to iterate and delete every element out of my vector. I am using push_back to add Lasers to my vector elsewhere in the code.

std::vector<Laser> m_Lasers;

for (int i = 0; i != m_Lasers.size(); i++)
{
    m_Lasers[i].ClearLaser();

    if (m_Lasers[i].GetX() > m_ScreenWidth || m_Lasers[i].GetX() < 0 || m_Lasers[i].GetY() < 0)
    {
        //erase the vector
        m_Lasers.erase(m_Lasers.begin() + i);
        i--;

    }
}

my =operator is defined as:

void operator=(const Laser& L){};

in my laser class. I think my issue may be with this.

Thank you so much for you help!

ColdFire
  • 31
  • 2

1 Answers1

6

What vector::erase does is moving all elements after the erased element forward using assignment, and then destroying the last element. It has to do this to maintain the invariant that the elements in the vector are stored contiguously.

For example, give a vector v of size 4, erasing v[1] essentially does v[1] = v[2]; v[2] = v[3]; v.pop_back(); (These are actually move assignments; std::move is omitted for clarity.)

If your assignment is a no-op (which is not allowed by erase's requirements, by the way), then this will just end up destroying the last element.

T.C.
  • 133,968
  • 17
  • 288
  • 421
  • 1
    Ah, I see whats happening then. So what should I change my assignment to? Sorry, I'm still new to all this. – ColdFire Feb 19 '15 at 05:59
  • 1
    Ah, I figured out a way around this issue. I can just use an array of pointers instead. Probably is a better way to do it anyway. – ColdFire Feb 19 '15 at 21:34