std::list remove element by index

13,500

I'd suggest using std::list::iterator instead of integer indices. std::list::erase() does not invalidate iterators.

auto index = myList.insert(myList.end(), element);

myList.erase(index);
Share:
13,500
KaareZ
Author by

KaareZ

Updated on June 04, 2022

Comments

  • KaareZ
    KaareZ almost 2 years

    I have a std::list full of objects. Whenever I add a object, I want to store that objects index in the list, so later on I can remove it from the list.

    What I want to do in pseudo code

    myList.pushBack(element);
    int index = myList.getIndexOfLastElement();
    
    myList.erase(index);
    

    For performance reasons I can't search by value.

    To clarify: I have element a(index 0), b(index 1), c(index 2), d(index 3)

    If I delete element b, I still want to be able to access c by 2.