How to remove an object from a list chained by the value of the attribute in C++?

Asked

Viewed 196 times

1

What is the best way to remove an element from a list by the value of its attribute, without knowing exactly its position?

I realized that the method Erase remove by position, and tried to use along with method find, but I couldn’t understand how to manipulate the return, nor how to pass the parameters correctly.

An example of object structure:

class Tipo{
    public:
        int id; // Esse valor é único para cada objeto
        float valor;
}

My attempt:

void remove_by_id(list<Tipo>& lsita, int id){

    // Essa linha não funciona pois o método find deveria receber o objeto e não o atributo (eu acho)
    lista.erase( find(lista.begin(), lista.end(), id) );
}


list<Tipo> minha_lista = {...}; // Lista com n elementos

remove_by_id(minha_lista, 3); // Remover o objeto que tem id == 3
  • Possible, but perhaps using a linked list instead of a vector. https://answall.com/q/163424/101

  • Okay, I’ll modify the question, because I wouldn’t know how to do it on a list either.

1 answer

1


It is possible to do this by implementing a Tipo for int, or polymorphism with a proxy type for Ids inherited by Tipo, or a builder to Tipo who receives int and makes the conversion implicit. However, I believe the simplest solution is to use an Higher-order Function.

auto remove_by_id(std::list<Tipo>& lista, int id)
{
    return lista.remove_if([&id](Tipo t) -> bool {
     return t.id == id; 
    });
}

Browser other questions tagged

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