Search code examples
c++c++11multimap

Multimap no match for operator==


I have this multimap inside a Bar class, with an unsigned long and a reference to the Foo class.

class Bar
{
//etc.
        struct map_sort
        {
            bool operator()(const unsigned long& e1, const unsigned long& e2) const
            {
                return (e2 < e1);
            }
        };

    std::multimap<const unsigned long,const Foo&, map_sort> m_map;

    find_and_erase(const unsigned long var1, const Foo& var2);
}

And now I want to retrieve all the values from the multimap and erase some.

void Bar::find_and_erase(const unsigned long var1, const Foo& var2)
{
    auto it = m_map.begin();

    for (it=m_map.begin(); it!=m_map.end(); ++it)
    {
        const unsigned long first = (*it).first;
        const Foo& second = (*it).second;
        if((first == var1) && (second == var2)) //<----ERROR No Match for operator==
            m_map.erase(it);
    }
}

Question

How can I compare the (second == var2) ?

(What I want is to find all entries from a multimap, and delete the ones on the find_and_erase() function, that matches the function argument. Don't know if there is an easier solution for this)


Solution

  • Define the equality function for Foos:

    bool operator==(const Foo& a, const Foo& b) {
        // return whether Foos are equal
    }
    

    If you define that one, you'll also want to define != for completeness:

    bool operator=!(const Foo& a, const Foo& b) { return !operator==(a,b); }
    

    Also, as per n.m.'s comment, given that you have a multimap you should take advantage of it:

    void Bar::find_and_erase(const unsigned long var1, const Foo& var2)
    {
        auto its = m_map.equal_range(var1);
        for (auto it = its.first; it != its.second; ++it) {
            if (it.second == var2) {
                m_map.erase(it);
            }
        }
    }