Search code examples
c++stlfindseterase

C++: Find and Erase a set element


i am having trouble to understand using find and erase with STL set. I have this:

struct NotMemberFound : exception {};

class FriendGroup
{
private:
    set<Person, ClassComp> members;
public:
    FriendGroup(): {}

    virtual void add_member(const Person& person)
    {
        members.insert(person);
        n_members = members.size();
    }

    virtual void remove_member(const Person& person)
    {
        const set<Person, ClassComp>::iterator it = members.find(person);

        if (it == members.end())
            throw NotMemberFound();
        else
        {
            members.erase(it);
        }
    }
}

Person have one attribute (String Name) and the metod get_name() that return his only attribute. And ClassComp its define like this:

struct ClassComp
{
    bool operator() (const Person& a, const Person& b) const
    {
        return a.get_name() != b.get_name();
    }
};

Well, when i am trying to use it like this:

int main(void)
{
    Person messi("Messi");
    Person xavi("Xavi");
    Person iniesta("Iniesta");

    FriendGroup barcelona;

    barcelona.add_member(messi);
    barcelona.add_member(xavi);
    barcelona.add_member(iniesta);

    barcelona.remove_member(iniesta);

    return 0;
}

The program throw an exception (NotMemberFound) when i call remove_member with the last element added. But if i try to erase any other member i don't have this problem.

What is wrong with my code?

// Sorry for my horrible English :S //


Solution

  • Your comparator should be

    struct ClassComp {
        bool operator() (const Person& a, const Person& b) const {
            return a.get_name() < b.get_name();
        }
    };
    

    The comparator should say if an element is inferior to another. In your case, it's like you said to the std::set that messi < xavi and that xavi < messi. When looking for an element, it cannot find it because it assumes they are sorted and it looks for them using binary search.