简体   繁体   English

c ++遍历对象列表并删除对象

[英]c++ Iterating over a list of objects and deleting a object

I have a list of objects and I want to delete a certain object once it hits the if condition. 我有一个对象列表,一旦遇到if条件,我想删除某个对象。 But I am having issues with it working. 但是我在工作中遇到了问题。 Mostly because the if condition is throwing the error. 主要是因为if条件引发错误。

Also I don't know if I need to create a temp folder value and let that be my if condition? 另外我也不知道是否需要创建一个临时文件夹值并将其作为我的if条件? I'm honestly kind of confused on iterators and any extra information might be helpful. 老实说,我对迭代器感到困惑,任何其他信息都可能会有所帮助。

void removeFolder(string fName)
{
    list<Folder> folders = this->getFolders();
    for (list<Folder> itr = folders.begin(); itr != folders.end();)
    {
        if (fName == *itr)
            itr = folders.erase(itr);
        else
            ++itr;
    }
}

I think you have correct idea, but you are doing wrong thing. 我认为您的想法正确,但是您做错了事。 folders is: 文件夹是:

list<Folder> folders

Than you are iterating different elements "folder" not "Folder": 比您要遍历不同的元素“文件夹”而不是“文件夹”:

for (list<folder> itr = folders.begin(); itr != folders.end();)

I think this should be rather: 我认为应该这样:

for (list<Folder>::iterator itr = folders.begin(); itr != folders.end();)

Now once you are iterating correct objects make comparisons that make sense, not string to object: 现在,一旦您迭代了正确的对象,就进行有意义的比较,而不是对象之间的字符串:

if (fName == *itr)

but rather compare string to string, I assume your Folder class has some method to get folder name ie: 而是将字符串与字符串进行比较,我假设您的Folder类具有某种获取文件夹名称的方法,即:

if (fName == (*itr).getFolderName())

I'm sure there is this question answered somewhere already, but the code is simple: 我确定这个问题已经在某个地方回答了,但是代码很简单:

You only need to use std::list<Folder>::remove_if() . 您只需要使用std::list<Folder>::remove_if()

void removeFolder(const std::string& fName)
{
    std::list<Folder>& folders = getFolders();
    folders.remove_if([&fName](Folder& item){return item.name == fName;});
}

As others have noted, there are other problems with your code that I've tried to fix. 正如其他人指出的那样,您尝试编写的代码还有其他问题。 In particular, you are probably comparing some sort of name member with the fName variable. 特别是,您可能正在将某种name成员与fName变量进行比较。 Also there is no need to pass the fName string by value into the removeFolder function, and presumably you need to modify not a local copy of folders , but some list existing outside of the function. 也没有必要通过fName通过值串入removeFolder功能,想必你需要不改变的本地副本folders ,但功能的一些列表现有的外线。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM