int main(){
vector<Customer*> newcustomer;
newcustomer.push_back(new Customer("III", 123333, 555));
newcustomer.push_back(new Customer("LOL", 122222, 444));
newcustomer.push_back(new Customer("PPL", 121111, 333));
for (int i = 0; i < 3; i++){
cout << newcustomer[i]->getName() << endl;
cout << newcustomer[i]->getPhone() << endl;
cout << newcustomer[i]->getID() << endl;
cout << endl;
}
system("pause");
return 0;
}
So I have made a class called customer, and you can insert new customer, getName returns the name, getPhone returns phone number and GetID returns ID, Now I want to earse everything off that vector, Not sure how to do it.
To erase all the elements from the vector your can simply use
myvector.erase (myvector.begin(),myvector.end());
or myvector.clear()
.
But here problem is not just erasing elements from vector but also deleting memory allocated on heap. Below is my solution.
int main(){
vector<Customer*> newcustomer;
newcustomer.push_back(new Customer("III", 123333, 555));
newcustomer.push_back(new Customer("LOL", 122222, 444));
newcustomer.push_back(new Customer("PPL", 121111, 333));
for (int i = 0; i < 3; i++){
cout << newcustomer[i]->getName() << endl;
cout << newcustomer[i]->getPhone() << endl;
cout << newcustomer[i]->getID() << endl;
cout << endl;
}
while(!newcustomer.empty())
{
Customer *cust = newcustomer.front();
newcustomer.erase(newcustomer.begin());
delete cust;
}
system("pause");
return 0;
}
If you simply want to erase everything off the vector, use: http://www.cplusplus.com/reference/vector/vector/erase/
It is the erase function for vectors
// erase the first 3 elements:
newcustomer.erase (newcustomer.begin(),newcustomer.begin()+3);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With