简体   繁体   中英

Debug assertion failed - vector iterators are incompatible

I'm trying to compare two iterators from the same vector, but for some reason it threw me this error:

That is the relevant code function:

function, which finds the first iterator and returns a copy of it:

static const vector<Player*>::const_iterator findPlayer(
                    const vector<Player*> players, int id)
{ ///const
    vector<Player*>::const_iterator found
        = find_if(begin(players), end(players), [id] (Player* player) {
            return player->getId() == id;
        });
    return found;
}

Those are the comparation strokes of code:

vector<Player*>::const_iterator found = findPlayer(this->_players_in, *cur_id);
if(found != end(this->_players_in))

Does somebody know the reason for that?

It looks like you're making a copy of the vector, using find_if to get an iterator into that copy, and returning that iterator. This is bad because the vector that iterator points into will be destroyed when you return.

You should pass players by reference instead. Your declaration should look like:

static const vector<player*>::const_iterator findPlayer(const vector<Player*>& players, int id)

(note the & )

This ensures that the iterator you return is pointing to the same container that the caller provided.

Note: this kind of assertion is not standard. It's quite kind of your compiler/environment to provide it for debug builds. I implemented these kinds of checks on some iterators for a custom container and it saved me on least a dozen occasions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM