'No matching function for call' error when inserting class into a STL map

22,618

Solution 1

You have a pointer to a map containing Foo values

std::map<unsigned int, Foo> *m_mapFoo;

and you are treating it as if it contained Foo pointer values:

std::map<unsigned int, Foo*> *m_mapFoo;

Try this:

m_mapFoo = new std::map<unsigned int, Foo>;
m_mapFoo->insert(std::make_pair(0, Foo(0)));
m_mapFoo->insert(std::make_pair(1, Foo(1)));

As for the second error, you have a pointer to a map, so you need

std::map<unsigned int, Foo>::iterator it = m_mapFoo->find(0);
if (it) {
  it->second.someFunctionIntoFooClass();
} else {
  // entry not found
}

Solution 2

Your map is typed to store objects of type Foo, not pointers to objects of type Foo. Seeing as you're trying to initialise the elements with new and access their members via ->, you probably want:

private:
    std::map<unsigned int, Foo*> *m_mapFoo;
Share:
22,618
Roman Rdgz
Author by

Roman Rdgz

Telecom Engineer

Updated on May 24, 2020

Comments

  • Roman Rdgz
    Roman Rdgz almost 4 years

    I have a STL map in C++ where the key is an unsigned int, and the value is a class whose constructor is:

    Foo::Foo(unsigned int integerValue){
        //Some stuff
    }
    

    At other class I have declarated the std::map at the header:

    private:
        std::map<unsigned int, Foo> *m_mapFoo;
    

    And at the cpp file I created it and inserted instances of Foo:

    m_mapFoo = new std::map<unsigned int, Foo>;
    m_mapFoo->insert(0, new Foo(0));
    m_mapFoo->insert(1, new Foo(1));
    

    But I'm getting the following error at the insert methods:

    no matching function for call to ‘std::map<unsigned int, Foo, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, Foo> > >::insert(const unsigned int&, Foo*)’
    

    Similar problem at find method:

    m_mapFoo.find(0)->second->someFunctionIntoFooClass();
    

    Where the error is exactly the following:

    request for member ‘find’ in ‘((Foo*)this)->Foo::m_mapGeoDataProcess’, which is of non-class type ‘std::map<unsigned int, Foo, std::less<unsigned int>, std::allocator<std::pair<const unsigned int, Foo> > >*’
    

    Additional notes: I don't have a Foo copy constructor, but I don't think that's the problem.

    Any help understanding this errors?

  • Roman Rdgz
    Roman Rdgz over 11 years
    That seems to work, thanks! But still having the second error at find method. Any idea?
  • juanchopanza
    juanchopanza over 11 years
    @RomanRdgz I added something about the second error. Beware that you should check the result of std::map::find.
  • Roman Rdgz
    Roman Rdgz over 11 years
    the error remains, the same: request for member find... I also have included <algorithm> with same results (I had forgotten)
  • juanchopanza
    juanchopanza over 11 years
    @RomanRdgz sorry, I had made a typo in the line where I use std::map::find and call teh Foo function. It should work now.