Search code examples
c++vectoriteratorunique-ptr

how to check if unique_ptr points to the same object as iterator


Let's consider such method:

void World::remove_organism(organism_iterator organism_to_delete)
{
    remove_if(begin(organisms_vector), end(organisms_vector), [](const unique_ptr<Organism>& potential_organism_to_del)
        {

        });
}

what I'm trying to achieve is to delete organism that iterator points to from vector<unique_ptr<Organism>>, so how am I supposed to compare unique_ptr<Organism> to std::vector<unique_ptr<Organism>>::iterator?


Solution

  • You don't have to search through the vector to find an iterator; you just have to erase it:

    void World::remove_organism(organism_iterator organism_to_delete)
    {
        organism_vector.erase(organism_to_delete);
    }
    

    Or if you want to delete only the element that the unique_ptr points to:

    void World::remove_organism(organism_iterator organism_to_delete)
    {
        organism_to_delete->reset();
    }