remove data from an object list

1

I'm having trouble removing an object from the list according to a code.

I tried to do this:

void turma::removeraluno (int matricula){
         // remover o aluno pelo codigo de matricula
    list<aluno>::iterator it;

for (it=lista.begin();it != lista.end();it++){

    if (it->getmatricula()== matricula) {
        lista.erase(it);

    } else{
        cout << "NAO ENCONTRADO "<<endl;
    }
}

But when I try to run the Memory Buffer error. I already tried with the remove too and it does not work

    
asked by anonymous 02.08.2017 / 08:46

2 answers

0

You can try.

for(int i;i<lista.size();i++){
    if(matricula==lista[i]){
        lista.erase(lista.begin()+i);
    }
}
    
02.08.2017 / 12:36
0

Your error results from using the iterator after you have called it in it. This results in undefined behavior.

You can do this as follows:

void turma::removerAluno (int matricula)
{
    for (list<aluno>::iterator it = lista.begin(); it != lista.end(); ++it)
    {
       if (it->getmatricula() == matricula) 
       {
           //lista.erase(it);
           it = lista.erase(it);        
       } 
    }
}
    
02.08.2017 / 16:30