Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ delete elements in vector

Tags:

c++

vector

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.

like image 685
Ggbeastboi Avatar asked Jan 09 '23 02:01

Ggbeastboi


2 Answers

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;

}
like image 135
HadeS Avatar answered Jan 18 '23 23:01

HadeS


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);
like image 45
Fuad Avatar answered Jan 18 '23 22:01

Fuad