samedi 28 février 2015

std::find_if for custom objects returns bad iterator when vector has at least 1 element

So I have a vector of objects of type Player. If I try to use std::find_if on that vector and use a lambda expression that return true only if the name if the player is a name I want to check against, it will work the first time if the vector is empty (as in the iterator is nullptr), but once I add a Player object in the vector, the find_if will return an iterator filled with random, bad data.


My code:



auto player = find_if(m_playerList.begin(), m_playerList.end(), [name](Player& p)
{
return p.Name == name;
});

if (player._Ptr != nullptr)
{
// Do stuff
}

else
{
Player newPlayer;
newPlayer.Name = name;
m_playerList.push_back(newPlayer);
}


So in the first iteration of this function, the player is nullptr, because the vector didn't contain any elements. In the second iteration, if I search by the same name, it finds it in the vector, however if I search by a different name, it returns an object with mangled, random data and the check "if (player._Ptr != nullptr)" passes.


Question is, what causes this? Am I checking the "player" object properly to figure out if the find_if actually found a valid object in the vector?


Aucun commentaire:

Enregistrer un commentaire