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?

1

1 Answer 1

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;});
Sign up to request clarification or add additional context in comments.

1 Comment

using for I am getting ‘room’ was not declared in this scope, and using remove_if: ‘ownerFd’ is not captured

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.