Arrrg 1991 again.
The first thing I just want to clarify is that new_acc2
is not in the vector. A copy of the variable new_acc2
was created in the vector.
The trouble is that new_acc1
, new_acc2
and new_acc3
all have the same value (basically no name and a zero balance). So when you placed them into the vector you got three copies of basically the same object. So how do you know which one you want to remove (they are all the same).
To remove something from a vector you should be able to uniquely identify it. So lets assume you gave each account a new unique name when you add it to the vector.
holding_vector.push_back(Account{"Bob", 10});
holding_vector.push_back(Account{"Mary", 20});
holding_vector.push_back(Account{"John", 40});
Now you want to remove "John"'s account. Then you can use the erase method.
// first you have to find a reference to the object you want
// to remove.
auto find = std::find_if(std::begin(holding_vector), std::end(holding_vector),
[](auto const& a){return a.name == "John";});
// If you found the item then you can remove it.
if (find != std::end(holding_vector)) {
holding_vector.erase(find);
}
Note: Above we had to use a specialized Lambda to tell the code how to check for a named account called "John". But you can make it easier by allowing the object to simply be compared against a string.
class Account {
public:
std::string name;
int balance;
bool operator==(std::string const& test) const {return name == test;}
};
Now you can simplify the above with the following erase:
// first you have to find a reference to the object you want
// to remove.
auto find = std::find(std::begin(holding_vector), std::end(holding_vector), "John");
// If you found the item then you can remove it.
if (find != std::end(holding_vector)) {
holding_vector.erase(find);
}