使用对象的索引从矢量中删除对象

Remove object from vector using its index

本文关键字:对象 删除 索引      更新时间:2023-10-16

>我有一个带有getType的私有成员类型的类,在第二个类中,我有一个这样的类向量,我可以根据需要添加到任意数量的类中,现在我想做的是,如果我被赋予一个"类型",我想通过使用该字符串找到该对象并擦除它,从该向量中删除整个对象。我已经尝试了下面的方法但没有奏效,也尝试了迭代器和模板,但似乎都不起作用。* 为了它而简化*

class AutoMobile{
private:
string type;
public:
AutoMobile(string type){
this->type = type;
}
string getType(){return type;}
};

class Inventory{
private:
vector<AutoMobile> cars;
public:
void removeFromInventory(string type){    // No two cars will have the same milage, type and ext
AutoMobile car("Ford");
cars.push_back(car);
for( AutoMobile x : cars){
cout<<x.getType();
}
for( AutoMobile x : cars){
if(x.getType() == "Ford"){
cars.erase(*x); // Problem i here, this does not work!
}
}
}
};
int main(void) {
Inventory Inven;
Inven.removeFromInventory("Ford");
return 0;
}

当您打算从std::vector中删除项目时,不宜使用范围for循环。请改用迭代器。

vector<AutoMobile>::iterator iter = cars.begin();
for ( ; iter != cars.end(); /* Don't increment the iterator here */ )
{
if ( iter->getType() == "Ford" )
{
iter = cars.erase(iter);
// Don't increment the iterator.
}
else
{
// Increment the iterator.
++iter;
}
}

您可以使用标准库函数和 lambda 函数来简化该代码块。

cars.erase(std::remove_if(cars.begin(),
cars.end(),
[](AutoMobile const& c){return c.getType() == 
"Ford";}),
cars.end());

您可以使用remove_if

cars.erase(std::remove_if(cars.begin(), 
cars.end(),
[=](AutoMobile &x){return x.getType()==type;}),
cars.end());