Ok I want to delete a element that cotains a artist that write in but how will i do that?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
elseif(i==6){
system("cls");
cout << "Look for artist and remove"<<endl;
cin >>search;
list<artist>::iterator it;
for(it=l1.begin() ;it!=l1.end();){
artist s = *it;
if(s.return_artist()==search){
l1.erase(it)//this doesnt work how should i write??
}
else{
cout <<"Artist not found" << endl;
}
}
}
For a start you never move the iterator forward after each check - so what you have is a infinite loop which just keeps rechecking the first item in the list.
The next step would be to write it like this:
**Example code;**
1 2 3 4 5 6 7 8 9 10 11
for (it = li.begin(); it != li.end(); it++)
{
if ( *it == check_value) //test if this is the one we want
{
li.erase(it); //match - Erase the entry from the list -
//WARNING - See further information below
}
}
Should you write your loop in that simple manner - you will find that
it will crash if it erases an entry from the list - BECAUSE ERASING AN ITEM FROM A LIST (OR ANY CONTAINER FOR THAT MATTER) WILL INVALIDATE
THE ITERATOR.
So you can do it in this manner
1 2 3 4 5 6 7 8 9 10 11 12 13 14
for (it = li.begin(); it != li.end(); it++)
{
if ( *it == check_value) //test if this is the one we want
{
li.erase(it); //match - Erase the entry from the list
//WARNING - we have invalidated out iterator because we have
//done a ERASE - so we need to rest our iterator to a safe value.
it = li.begin(); //In this case I rest the iterator to the beginning.
}
}
Note:
In the example above we make sure we get all the way through
the list and erase any matching entries.
If you only want to ease the first item that matches - you could usebreak; to leave the loop at that point (instead of resetting the iterator back to the start );