std::list::erase not working

后端 未结 3 1109
天涯浪人
天涯浪人 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:41

    First, you need to pass the list by reference; your code is working on a copy, so changes it makes won't affect the caller's list:

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

    Second, erasing a list element invalidates any iterator that refers to that element, so attempting to carry on iterating afterwards will cause undefined behaviour. If there will only be one element to remove, then return from the function straight after the call to erase; otherwise, the loop needs to be structured something like:

    for (auto it = list.begin(); it != list.end(); /* don't increment here */) {
        if (it->ID == id) {
            it = list.erase(it);
        } else {
            ++it;
        }
    }
    

提交回复
热议问题