How to insert data into map where one parameter is an object?

262 views Asked by At

I have a class Normal defined as:

    class Normal
    {
        bool value;
        float time;
        public:
            Normal(bool val,float time): value(val),time(time) {}
    }

Also, I have declared a map variable as:

    map<string,Normal> myMap;

Now I want to insert an data into this map. Is this way of inserting correct?

    Normal temp(true,45.04);
    myMap.insert(pair<string,Normal>("one",temp));

or

    myMap["one"]=temp;

How should i insert data into the map?

2

There are 2 answers

14
Spanky On BEST ANSWER

Use this code

Normal *temp =  new Normal(true,45.9);
mymap.insert(make_pair("one",temp));

avoid shallow copy since pointer is involved.

EDIT: Use insert function to insert data in map. Index is not the best way. specially when u r accessing See this link for details In STL maps, is it better to use map::insert than []?

EDIT2: For deletion,use the below code.

for(std::map<string, Normal*>::iterator itr = mymap.begin();it !=  mymap.end();)
{
  if(it->second != NULL)
   {
      delete (it->second);
      (it->second) = NULL;
      it=mymap.erase(it);
    }
    else
    {
         ++it;
    }

  }
0
Quentin On

In C++03 :

myMap.insert(std::make_pair(
    "one",
    Normal(true, 45.04)
));

In C++11 :

m.emplace(std::piecewise_construct,
          std::forward_as_tuple("one"),
          std::forward_as_tuple(true, 45.04)
);

Both avoid default-constructing a key-value pair inside operator[] and then overwriting it.