I need help writing a piece of code that will search a vector for the object who's mLastName member is the same as the name that the user is searching for. Once found, it must be deleted and the vector must delete the empty space.
Here is what i have so far but the code is not valid at all.
1 2 3 4 5 6 7 8 9 10 11 12
std::string name;
cout << "Enter the last name of the Employee you would like "
<< "to delete: ";
cin >> name;
for (int i = 0, i < database.size; i++)
{
if(database[i].mLastName == name)
{
delete database[i];
database.pop_back();
}
}// end for
The ones after if... (the curly ones, mind you)
And after the deed is done, you should break out of the loop (or if you want to remove all matches, you need to decrement i before the next iteration so you don't skip the next element - although in that case std::remove_if is preferable anyway).
Athar im not really sure what you mean. BUT, here is my code at the moment.
PROBLEMS
>in the second forloop parameter it says "variable i is not a template" and database must have a constant value
>in the if parenthesis and inside the if it says database must have a class type
1 2 3 4 5 6 7 8 9 10 11 12 13
std::string name;
cout << "Enter the last name of the Employee you would like "
<< "to delete: ";
cin >> name;
for (int i = 0, i < database.size; i++)
{
if(database.at(i).mLastName == name)
{
database.erase(database.begin()+i;
database.pop_back();
break;
}
}// end for
You declared database as an array. Therefore you must specify which element you mean. Since there's just one, that's database[0].
In the code snippet above, you wrote , instead of ; in line 5 and you forgot a closing brace in line 9.
Line 10 needs to go. It removes the last element in the vector, which makes no sense.
Okay i changed the vector from an array. The database i bolded says expression must have a class type. I know that the code is wrong but im not sure how to do it. What im trying to do is
if(object stored in database[i] == name)
my code is
1 2 3 4 5 6 7 8 9 10 11 12
std::string name;
cout << "Enter the last name of the Employee you would like "
<< "to delete: ";
cin >> name;
for (int i = 0; i < database.size(); ++i)
{
if(database[i].mLastName == name)
{
database.erase(database.begin()+i);
break;
}
}// end for