Rom*_*dgz 9 c++ dictionary stl std
我在C++中有一个STL映射,其中键是unsigned int,值是一个构造函数为的类:
Foo::Foo(unsigned int integerValue){
//Some stuff
}
Run Code Online (Sandbox Code Playgroud)
在其他类中,我在头部声明了std :: map:
private:
std::map<unsigned int, Foo> *m_mapFoo;
Run Code Online (Sandbox Code Playgroud)
在cpp文件中我创建了它并插入了Foo的实例:
m_mapFoo = new std::map<unsigned int, Foo>;
m_mapFoo->insert(0, new Foo(0));
m_mapFoo->insert(1, new Foo(1));
Run Code Online (Sandbox Code Playgroud)
但是我在插入方法中遇到以下错误:
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*)’
Run Code Online (Sandbox Code Playgroud)
find方法的类似问题:
m_mapFoo.find(0)->second->someFunctionIntoFooClass();
Run Code Online (Sandbox Code Playgroud)
错误的地方如下:
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> > >*’
Run Code Online (Sandbox Code Playgroud)
附加说明:我没有Foo复制构造函数,但我不认为这是问题所在.
有什么帮助理解这个错误?
您有一个指向包含Foo值的地图的指针
std::map<unsigned int, Foo> *m_mapFoo;
Run Code Online (Sandbox Code Playgroud)
你正在将它视为包含Foo指针值:
std::map<unsigned int, Foo*> *m_mapFoo;
Run Code Online (Sandbox Code Playgroud)
试试这个:
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)));
Run Code Online (Sandbox Code Playgroud)
至于第二个错误,你有一个指向地图的指针,所以你需要
std::map<unsigned int, Foo>::iterator it = m_mapFoo->find(0);
if (it) {
it->second.someFunctionIntoFooClass();
} else {
// entry not found
}
Run Code Online (Sandbox Code Playgroud)