I am working on one of the project which requires
class MyObj; map<string, MyObj*> myMap;
Here logic is here to map file name to MyObj class.
If I try to insert following
string strFilename = "MyFile"; MyObj* pObj = new MyObj(); myMap.insert(strFileName, pObj); // This line throwing following error.
no matching function for call to
'std::map<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, void*, std::less<std::basic_string<char, std::char_traits<char>, std::allocator<char> > >, std::allocator<std::pair<const std::basic_string<char, std::char_traits<char>, std::allocator<char> >, void*> > >::insert(std::string&, void*)'
Can any one please help me how to solve this. Are is there better way we can do this using STL
Here logic is here to map file name to MyObj class. string strFilename = "MyFile"; MyObj* pObj = new MyObj(); myMap. insert(strFileName, pObj); // This line throwing following error. Use the toolbar buttons above the text field to control the formatting of your question.
C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.
Maps are associative containers that store elements in a combination of key values and mapped values that follow a specific order. No two mapped values can have the same key values. In C++, maps store the key values in ascending order by default. A visual representation of a C++ map.
Hi Naveen, *You can Create map of both String and Integer, just keep sure that your key is Unique.
I've typedef'd this stuff to make it more readable...
typedef std::map<std::string, MyObj*> MyMap; typedef std::pair<std::string, MyObj*> MyPair; MyMap myMap; string strFilename = "MyFile"; MyObj* pObj = new MyObj(); myMap.insert(MyPair(strFilename, pObj));
std::map requires a pair when you use the insert function.
You have two options, either:
myMap[strFileName] = pObj;
Or:
myMap.insert(std::make_pair(strFileName,pObj));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With