mardi 1 juillet 2014

How to use correct pointer for find and find_if when dealing with vector


Vote count:

0




I have a structure like this:



struct client
{
string name;
double money;
};


I also have 2 predicates:



bool less_10(const client& a)
{
return a.money < 10;
}

bool not_a(const client& a)
{
return a.name.at(0) != 'A';
}


In my main function I use this to filter out the result stored in vector client_list (everyone with money < 10 (choice 1) or everyone with name not start with A (else))



if (choice_filter == 1)
{
vector<client>::iterator it3;
it3 = find_if(client_list.begin(), client_list.end(), less_10);
while (it3 != client_list.end())
{
**client_list.erase(it3);
it3 = find_if(it3 + 1, client_list.end(), less_10);
}
client_list.erase(it3);**
}

else
{
vector<client>::iterator it4;
it4 = find_if(client_list.begin(), client_list.end(), not_a);

while (it4 != client_list.end())
{
**client_list.erase(it4);
it4 = find_if(it4 + 1, client_list.end(), not_a);
}
client_list.erase(it4);**
}


I notice that if I erase first, then find_if, i'll lost the last client. So i added 1 more line to erase, but the program crashes as iterator is now at the end, cant erase.


Is there any way to get around this? I want to keep using find_if with predicates as well as while loop like above as they are required.



asked 44 secs ago






Aucun commentaire:

Enregistrer un commentaire