使用对象的索引从矢量中删除对象
Remove object from vector using its index
>我有一个带有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());
相关文章:
- 线程调用的函数对对象删除是否安全?
- 当我使用dynamic_cast并删除对象删除时,析构函数是如何工作的?
- 使用 com 对象删除计划任务
- C 将对象删除为参考
- C样式对象删除的包装器
- 静态映射中动态分配的对象.删除必要的
- C++指向对象删除的指针数组,"Debug assertion failure!"
- 在其成员函数返回之前,将对象删除是不确定的行为吗?
- Python 对象删除检测
- C++安全对象删除
- Qt:RemoveWidget和对象删除
- Qt对象删除导致崩溃
- 删除由两个shared_pointer实例管理的对象(删除其中一个)
- 顶点缓冲区对象(删除进程)opengl
- 设计 -- 按名称或对象删除
- 提升中的异常:进程间,共享内存对象删除
- 使用std::function和std::bind来存储回调并处理对象删除
- 如何使用智能指针防止双重对象删除
- 指针指向对象删除时自动为空
- 对象层次结构中的对象删除责任