Jake Young
Jake Young

Reputation: 83

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

Upvotes: 0

Views: 171

Answers (2)

Temple
Temple

Reputation: 1631

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 i.e:

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

Upvotes: 2

PlinyTheElder
PlinyTheElder

Reputation: 1494

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.

Upvotes: 0

Related Questions