繁体   English   中英

使用索引从向量中删除对象

[英]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;
}

您可以使用remove_if

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

当您打算从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());

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM