You remove elements the same way you remove any elements from any std::vector
- via the std::vector::erase()
method, for instance. All you need for that is an iterator
to the desired element to remove.
In your case, since you are storing std::shared_ptr<std::string>
objects rather than storing actual std::string
objects, you may need to use something like std::find_if()
to find the vector element containing the desired string value, eg:
void removeEnemy(string name)
{
auto iter = std::find_if(enemy.begin(), enemy.end(),
[&](auto &s){ return (*s == name); }
);
if (iter != enemy.end())
enemy.erase(iter);
}
UPDATE: in the new code you have added, you are incorrectly mixing indexes and iterators together. You are creating an infinite loop if the vector
is not empty, as you never increment the it
iterator that controls your loop, you are incrementing your index i
variable instead (see what happens when you don't give your variables unique and meaningful names?). So you end up going out of bounds of the vector
into surrounding memory. That is why you get the segfault error.
Even though you are (trying to) use an iterator to loop through the vector
, you are using indexes to access the elements, instead of dereferencing the iterator to access the elements. You don't need to use indexes at all in this situation, the iterator alone will suffice.
Try this instead:
void RemoveEnemy( vector<shared_ptr<Enemy>> & chart, string id )
{
for(auto it = chart.begin(); it != chart.end(); ++it)
{
if (id == it->GetEnemyID() )
{
chart.erase(it);
return;
}
}
Or, using the kind of code I suggested earlier:
void RemoveEnemy( vector<shared_ptr<Enemy>> & chart, string id )
{
auto iter = std::find_if(chart.begin(), chart.end(),
[&](auto &enemy){ return (enemy->GetEnemyID() == id); }
);
if (iter != chart.end())
chart.erase(iter);
}