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
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
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: