Reputation: 1138
I have stored objects in a vector, where each object has a staff number property. If a user wants to delete an object from the vector, the user can enter the staff number so that the specific object will get deleted from the vector.
void Administrator::deleteMember()
{
string staffNumber;
FileHandler<Administrator> adminTObj;
cout<<"Enter Staff Number of the Member to Delete"<<endl;
cin>>staffNumber;
if(staffNumber.find("Ad"))
{
vector<Administrator> myVec=adminTObj.getVectorAdministrator();
for(Administrator iter:myVec)
{
if(iter.getStaffNumber()==staffNumber) //checks if the staff number matches an object's staff number
{
// If it matches it should delete the record (Need to implement)
}
}
}
}
How do I delete the object from the vector?
Upvotes: 1
Views: 118
Reputation: 227418
If you have a single element, you can use std::find_if
to get an iterator to the element, and std::vector::erase
to remove it.
auto it = std::find_if(myVec.begin(),
myVec.end(),
[staffNumber](const Administrator& a)
{ return a.getStaffNumber() == staffNumber; });
myVec.erase(it);
If you want to remove all elements satisfying a criterion, use std::remove_if
and std::vector::erase
(the erase-remove idiom).
auto it = std::remove_if(myVec.begin(),
myVec.end(),
[staffNumber](const Administrator& a)
{ return a.getStaffNumber() == staffNumber; });
myVec.erase(it, myVec.end());
Upvotes: 6
Reputation: 2359
This is how to erase a specific item from the vector by its index id.
int at;
vector<Administrator> myVec=adminTObj.getVectorAdministrator();
at = indexToErase;
myVec.erase(myVec.begin()+at)
Upvotes: 0
Reputation: 17605
You could use the erase
method, which is documented here; however you should break the loop immediateley afterwards, as the call of erase
would perhaps invalidate the iterator.
Upvotes: 0
Reputation: 56557
Use the member function vector::erase()
, see http://www.cplusplus.com/reference/vector/vector/erase/
Upvotes: 0