0

my code is:

class Room {
public:
    int id;
    string name;
    int ownerFd;

    Room(int id, string name, int ownerFd)
    {
        this->id = id;
        this->name = name;
        this->ownerFd = ownerFd;
    }
};

void RemoveUserRooms(int ownerFd) {
    for(auto& room : rooms) {
        if (room.ownerFd == ownerFd) {
            //remove room from list
        }
    }
}

What I want to do is to remove object from list. I already tried with remove and erase but that seems not to work in this way. Is is possible to do with list?

David Konn
  • 29
  • 4
  • Possible duplicate of [Can you remove elements from a std::list while iterating through it?](https://stackoverflow.com/questions/596162/can-you-remove-elements-from-a-stdlist-while-iterating-through-it) – 1201ProgramAlarm Jan 04 '18 at 05:03

1 Answers1

2

Use iterator and erase while properly updating the iterator.

    for(auto i=rooms.begin();i!=rooms.end();)
    {
        if((*i).ownerFd == ownerFd)
        i=rooms.erase(i);
        else
        i++;
    }

Or better , you can use remove_if

rooms.remove_if([ownerFd](Room i){return i.ownerFd == ownerFd;});
Gaurav Sehgal
  • 7,422
  • 2
  • 18
  • 34
  • using `for` I am getting `‘room’ was not declared in this scope`, and using `remove_if`: `‘ownerFd’ is not captured` – David Konn Jan 04 '18 at 05:14