remove data from an object list

Asked

Viewed 57 times

1

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

I tried to do so:

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 execute the error of memory buffer. I’ve tried with remove too and it doesn’t work

2 answers

0

you can try.

for(int i;i<lista.size();i++){
    if(matricula==lista[i]){
        lista.erase(lista.begin()+i);
    }
}
  • Thus ai gave the following error : error: no match for ?Operator[]' (operand types are ?Std::__cxx11::list<pupil>' and ?int')|

0

Your error results from using the iterator after calling Rase on it. This results in undefined behavior.

You can do it this way:

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);        
       } 
    }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.