gpt4 book ai didi

c++ - 使用其索引从 vector 中删除对象

转载 作者:行者123 更新时间:2023-11-28 01:34:05 24 4
gpt4 key购买 nike

我有一个带有私有(private)成员类型的类,其中有一个 getType,在第二个类中,我有一个此类的 vector ,我可以根据需要添加到任意多个类中,现在我想做的是,如果我被赋予了一个“类型”我想通过使用该字符串找到该对象并将其删除来从该 vector 中删除整个对象。我试过下面的方法但没有用,也试过迭代器和模板但似乎都没有用。 *这是为了简化它*

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 中删除项目时,使用 range 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());

关于c++ - 使用其索引从 vector 中删除对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50127683/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com