samedi 29 décembre 2018

Deleting a pointer from a vector using loops (not iterators)

I have a method that is passed an object, finds that object in a vector of pointers by matching its address in a loop, and needs to remove the matching item from the vector without deleting the item (i.e the item needs to still exist in memory). Currently, this is the method:

void remove(Soldier& soldier) {
    for (size_t i = 0; i < armySize(); ++i) {
        if (army[i] == &soldier) {
            cout << army[i]->getName() << "is removed" << endl;
            army.erase(i);
            break;
        }
    }
}

Where soldier is the object that needs to be removed and army is a vector of Soldier pointers. The if statement works, meaning that the address of soldier and an item in the vector matches. The problem is that I get an error that says "no matching member function for call to 'erase'". How would I fix this without using iterators (no new, delete or begin method)?

Aucun commentaire:

Enregistrer un commentaire