0

I am trying to erase an element in a vector in C++ with the erase method like this:

player_animals.erase(second_parameter); 

Please note that second_parameter is an integer e.g. 2

and the player_animals is a vector of Animal pointers defined like this: vector<Farm::Animal *>animals_;

and the error I get about erase is:

no instance of overloaded function "std::__1::vector<_Tp, _Allocator>::erase [with _Tp=Farm::Animal *, _Allocator=std::__1::allocator<Farm::Animal *>]" matches the argument list -- argument types are: (unsigned int) -- object type is: std::__1::vector<Farm::Animal *, std::__1::allocator<Farm::Animal *>> 

The code where I use the erase method is as follows:

 if (animal_to_be_sold->getType() == SellCommand::SELL_FARM_ANIMAL) { Farm::FarmAnimal* animal_to_be_sold = static_cast<FarmAnimal*> (animal_to_be_sold); player.putAnimalInSold(animal_to_be_sold); player_animals.erase(second_parameter); player.addMoney(SellCommand::FARM_ANIMAL_PRICE); } else { player.addMoney(SellCommand::PET_PRICE); player_animals.erase(second_parameter); } 

How could I fix this so I can use the erase method to remove an element in the vector at a position

1 Answer 1

1

I think this will work because std::vector::erase function requires iterator:

player_animals.erase(player_animals.begin() + second_parameter); 
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but it seems to not do anything, after getting the size of the vector before and after erase, it is the same
Please make sure that you are using the function size() instead of capacity() otherwise it should work unless the second_parameter is off limits of vector.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.