Reputation: 3
I have a class with a private member type with a getType in it, in a second class I have a vector of such class that I can add to as many classes as I want, now want I want to do is if I was given a "Type" I want to remove the whole Object from such vector by finding that object using that string and erase it. I have tried the way below but did not work, also tried iterators and templates yet none seem to work. * This is simplified for the sake of it*
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;
}
Upvotes: 0
Views: 75
Reputation: 206567
Use of range for
loop is not appropriate when you intend to remove items from a std::vector
. Use an iterator instead.
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;
}
}
You can simplify that block of code by using standard library functions and a lambda function.
cars.erase(std::remove_if(cars.begin(),
cars.end(),
[](AutoMobile const& c){return c.getType() ==
"Ford";}),
cars.end());
Upvotes: 1
Reputation: 7542
You can use remove_if
cars.erase(std::remove_if(cars.begin(),
cars.end(),
[=](AutoMobile &x){return x.getType()==type;}),
cars.end());
Upvotes: 1