1

What's the difference between those two versions of insertion into a c++ map :

map<string,double> myMap;
// version 1
myMap["david"] = 123.123;

// version 2
myMap.insert(std::make_pair("david" ,123.123));

Regards

JAN
  • 21,236
  • 66
  • 181
  • 318
  • 1
    [this](http://stackoverflow.com/questions/4286670/how-do-i-insert-into-a-map) might help. – axiom Dec 01 '12 at 14:55

1 Answers1

5

The first one will update the value if the key already exists, but the second one will not update it if the key already exists.

std::map<string,double> myMap;

//working with operator[]
myMap["david"] = 123.0; //inserts
myMap["david"] = 98.0;   //updates

std::cout << myMap["david"] << std::endl; //prints 98.0 (updated value)

//working with insert
myMap.insert(std::make_pair("nawaz", 100.0)); //inserts
myMap.insert(std::make_pair("nawaz", 878.0)); //no update

std::cout << myMap["nawaz"] << std::endl; //prints 100.0 (old value)

The insert function returns std::pair<iterator,bool>. The boolean value of the pair tells you whether the insertion was successful or not.

Now read the documentation for more detail:

Nawaz
  • 353,942
  • 115
  • 666
  • 851
  • In addition, if the value at `myMap["david"]` does not exist, it is default-constructed and then overwritten (which is why you can't use `operator[]` with maps that are `const`). This is less optimal than `insert`. Likewise, `insert` is probably less optimal in this case than `emplace`. – moswald Dec 01 '12 at 15:05