如何从C ++中的向量中删除元素

问题描述 投票:0回答:1

我正在尝试使用erase这样的方法在C ++中擦除向量中的元素:

player_animals.erase(second_parameter); 

请注意,second_parameter是整数e.g. 2

[player_animals是动物指针的向量,定义如下:vector<Farm::Animal *> animals _;

我得到的关于擦除的错误是:

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 *>>

我使用擦除方法的代码如下:

 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); 

            }

如何解决此问题,以便可以使用擦除方法从某个位置移除向量中的元素

c++ vector
1个回答
1
投票

我认为这将起作用,因为std :: vector :: erase函数需要迭代器:

player_animals.erase(player_animals.begin() + second_parameter);
© www.soinside.com 2019 - 2024. All rights reserved.