Search code examples
c++11insertmultimap

How to insert a reference to a multimap?


I have a class Foo that contains a multimap with an unsigned long and a reference to a Bar class.

I'm getting the error "no matching function to call multimap, etc".

What is wrong on my insert into the multimap?

[header file]

class Foo
{
public:

    Foo();

    ~Foo();

    void set(const unsigned long var1, const Bar& var2);

private:

    struct map_sort
    {
        bool operator()(const unsigned long& e1, const unsigned long& e2) const
        {
            return (e2 < e1);
        }
    };

    std::multimap<unsigned long,Bar&, map_sort> m_map;
};

[source file]

void Foo::set(const unsigned long var1, const Bar& var2)
{
    m_map.insert(var1,rtime); //<-- ERROR!!!!!!!!
}

Solution

  • You multimap member is declared to take unsigned long and Bar&

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

    while, in source file

    void Foo::set(const unsigned long var1, const Bar& var2)
    {
        m_map.insert(var1,rtime); //var1 is const here! (rtime is not declared but I assume you meant var2 - which is const, too)
    }
    

    you are trying to insert const unsigned long and const Bar& which differ from the ones declared above (they are constant). Note that the const unsigned long isn't really an issue because it is copied by value so, in fact, the multimap keeps its own version of the variable and the "main" one can't be modified whatsoever.

    Additionally, check out the documentation of multimap's insert method http://www.cplusplus.com/reference/map/multimap/insert/. You should use std::pair to insert key-value pair:)

    Solution 1: Change your method to take non-const arguments:

    void set(unsigned long var1, Bar& var2);
    

    Solution 2: Change your map to contain const values:

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

    Working example:

    class Foo
    {
    public:
    
        Foo();
    
        ~Foo();
    
        void set(const unsigned long var1, const Bar& var2);
    
    private:
    
        struct map_sort
        {
            bool operator()(const unsigned long& e1, const unsigned long& e2) const
            {
                return (e2 < e1);
            }
        };
    
        std::multimap<const unsigned long, const Bar&, map_sort> m_map;
    };
    
    void Foo::set(const unsigned long var1, const Bar& var2)
    {
        m_map.insert(pair<const unsigned long, const Bar&>(var1, var2));
    }