Search code examples
c++pointersstdmap

How to insert into `std::map<string, double>* myMap`?


I have initialized a map like this:

map<string, double>* myMap = new map<string, double>();

this declaration cannot change!

I tried to insert into it like:

myMap["hi"] = 20.0;

and

myMap->insert ("hi", 20.0);

What is the correct way?


Solution

  • myMap is the pointer in your case. Why do you allocate the map with new? Do it like this:

    map<string, double> myMap;
    myMap["hi"] = 20.0;
    

    Or if you still want to allocate it dynamically, then dereference the pointer

    (*myMap)["hi"] = 20.0;
    

    or call operator[] with ->:

    myMap->operator[]("hi") = 20.0;
    

    insert expects std::map::value_type which is std::pair<const string, double> in your case. Call it like this:

    myMap->insert(make_pair("hi", 20.0));
    

    or

    myMap->insert({"hi", 20.0});
    

    Note that if an entry with the same key already exists, using square brackets (either form) will replace the value of that entry, and using insert (either form) will do nothing and leave the previous value alone. (from @aschepler comment)