std::list::erase not working

后端 未结 3 1114
天涯浪人
天涯浪人 2020-12-20 08:13

I am trying to delete an element from a list of objects if one of the object\'s properties matches a condition. This is my function to do so, however, after performing this

3条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-20 08:36

    The reason you see no changes reflected is that your list is not being passed by reference, so you are only removing elements from a copy of the list.

    Change it to this:

    void FileReader::DeleteProcess(int id, list &listToDeleteFrom) //note &
    

    This will keep the same syntax in the function and modify the original.

    However, the way you're deleting the elements is a bit sub-optimal. If you have C++11, the following will remove your invalidation problem, and is more idiomatic, using an existing algorithm designed for the job:

    listToDeleteFrom.erase ( //erase matching elements returned from remove_if
        std::remove_if( 
            std::begin(listToDeleteFrom), 
            std::end(listToDeleteFrom), 
            [](const Process &p) { //lambda that matches based on id
                return p->ID == id;
            }
        ),
        std::end(listToDeleteFrom) //to the end of the list
    );
    

    Note the keeping of std::list<>::erase in there to actually erase the elements that match. This is known as the erase-remove idiom.

提交回复
热议问题