Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: error: vector subscript out of range. when erasing objects in the vector  (Read 1432 times)

0 Members and 1 Guest are viewing this topic.

Baduo127

  • Newbie
  • *
  • Posts: 2
    • View Profile
I'm trying to create a vector which contains several rectangles (blockRect) in the block class, when the third rectangle (blockRect) in the vector array hit another rectangle (endRect) defined in another class, it (the third blockRect in the vector) should be deleted in the vector, but it gives me a error: vector subscript out of range, I can't figure out why, any help please?

this is the code which I try to delete the third blockRect in the vector (there is 4 blockRect in Vec1, and Vec 2 basicly contains endRect for collision):

for (int i = 0; i < Vec2.size(); i++) {
        if (Vec2.endRect.getGlobalBounds().intersects(blocksClass.Vec1[2].blockRect.getGlobalBounds())) {
            blocksClass.Vec1.erase(blocksClass.Vec1.begin() + 2);
    }
}


eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 10815
    • View Profile
    • development blog
    • Email
You shouldn't work with magic numbers such as 2, especially if you're iterating over a vector and at the same time remove elements. Whenever you access a random element in a vector you should make sure that it actually exists, by checking against the vector's size.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/

Hapax

  • Hero Member
  • *****
  • Posts: 3351
  • My number of posts is shown in hexadecimal.
    • View Profile
    • Links
I'm curious as to your creation of the vector (Vec1). You say that they are a vector of blockRect but it looks like blockRect is a member of whatever the vector is actually holding.

Similar to Exploiter's comment, any reason you're blindly removing a specific element regardless of how many times you do this loop?
Selba Ward -SFML drawables
Cheese Map -Drawable Layered Tile Map
Kairos -Timing Library
Grambol
 *Hapaxia Links*

Mortal

  • Sr. Member
  • ****
  • Posts: 284
    • View Profile
i think there is mistake in your code snippet, Vec2.endRect should be some thing like this vec2[i].endRect.