-2

I have code -

    for (auto i = _entities.begin(); i != _entities.end();) {
        std::shared_ptr<Entity> entity = *i;

        if (entity == nullptr || entity->is_dead()) {
            i = _entities.erase(i);
            continue;
        }

        entity->update(diff);
        ++i;
    }

I get this error -

can't increment invalidated vector iterator

for the last line. I don't know how it is causing the vector to be invalidated. enter image description here

SagunKho
  • 985
  • 10
  • 26
  • Please try to create a [mre], and [edit] your question to show it to us. Also please use a [*debugger*](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems) to catch the crash (which I assume it is) to locate exactly when and where in your code it happens. – Some programmer dude Aug 16 '23 at 06:29
  • The shown code looks ok. Is anything else modifying `_entities`? Do you have other threads maybe? – Alan Birtles Aug 16 '23 at 06:31
  • @AlanBirtles I do have other threads but they don't intersect in this function. Each thread has its own `_entities` vector. – SagunKho Aug 16 '23 at 06:33
  • @SagunKho The code above does not invalidate any iterators, so something else is going on, presumably thread related. – john Aug 16 '23 at 06:42
  • Where in ***your*** code does it happen? Please walk up the call-stack until you get to your code. – Some programmer dude Aug 16 '23 at 06:51
  • And as mentioned, the code you show is fine, on its own. The problem lies somewhere else. It's very hard to help you without a [mre]. – Some programmer dude Aug 16 '23 at 06:52
  • And if you haven't done it before, then please take some time to read about [how to write the "perfect" question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/), especially its [checklist](https://codeblog.jonskeet.uk/2012/11/24/stack-overflow-question-checklist/). – Some programmer dude Aug 16 '23 at 06:53

0 Answers0