简体   繁体   中英

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. But I am having issues with it working. Mostly because the if condition is throwing the error.

Also I don't know if I need to create a temp folder value and let that be my if condition? 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:

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() .

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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