Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to store pointers in map

Tags:

c++

map

stl

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

like image 948
Venkata Avatar asked Nov 03 '10 14:11

Venkata


People also ask

How do you store a pointer on a map?

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.

Can you use a pointer as a key in a map?

C++ standard provided specialisation of std::less for pointers, so yes you can safely use them as map keys etc.

How does map store values in C++?

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.

Can we store string in map?

Hi Naveen, *You can Create map of both String and Integer, just keep sure that your key is Unique.


2 Answers

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)); 
like image 156
Moo-Juice Avatar answered Sep 18 '22 22:09

Moo-Juice


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)); 
like image 43
robev Avatar answered Sep 17 '22 22:09

robev