std :: list :: erase不工作 [英] std::list::erase not working

查看:108
本文介绍了std :: list :: erase不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果对象的某个属性与某个条件匹配,我将尝试从对象列表中删除该元素。这是我的功能,但是,执行此操作,然后打印内容,erase()似乎没有效果。我在这里做错了什么?

  void FileReader :: DeleteProcess(int id,list< Process> listToDeleteFrom)
{
list<过程> ::迭代器过程;

for(process = listToDeleteFrom.begin(); process!= listToDeleteFrom.end(); process ++)
{
if(process - > ID == id)
{
listToDeleteFrom.erase(process);
}
}
}


解决方案>

首先,你需要通过引用传递列表;您的代码正在处理一个副本,因此更改不会影响调用者的列表:

  void FileReader :: DeleteProcess int id,list< Process>& listToDeleteFrom)
^

元素无效任何引用该元素的迭代器,因此尝试继续进行迭代将导致未定义的行为。如果只有一个元素要删除,则在调用 erase 后直接从函数返回;否则,循环需要结构化为:

  for(auto it = list.begin(); it!= list .end(); / *不在这里增加* /){
if(it-> ID == id){
it = list.erase
} else {
++ it;
}
}


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 operation and then printing the contents, the erase() seems to have no effect. What am I doing wrong here?

void FileReader::DeleteProcess(int id, list<Process> listToDeleteFrom)
{
    list<Process>::iterator process;

    for(process = listToDeleteFrom.begin(); process != listToDeleteFrom.end(); process++)
    {
        if (process -> ID == id)
        {
            listToDeleteFrom.erase(process);
        }
    }
}

解决方案

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<Process> & 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;
    }
}

这篇关于std :: list :: erase不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆