I was asked the two ways to insert a record to a map,
mymap["foo"] = 123;
mymap.insert("foo", 123);
so is there any difference between these two except the syntax?
In addition to Timo's excellent answer--
If no element at "foo" exists, the first will first default construct a value at the "foo" location, THEN using a reference to the default constructed "foo" value, assign 123 to that location.
Just doing
mymap["foo"]
will cause a value to be default constructed and placed at the "foo" location. So be careful when doing
int value = mymap["foo"]
because it will work, even if you never explicitly assigned or inserted at foo
There is, the first option via []
will overwrite the value stored with the key "foo" if a key "foo" exists, whereas insert
will fail to insert data if the key already exists and will indicate success or failure in its return value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With