Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

difference between two ways to insert into map

Tags:

c++

map

stl

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?

like image 482
skydoor Avatar asked Dec 05 '22 22:12

skydoor


2 Answers

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

like image 136
Doug T. Avatar answered Jan 03 '23 20:01

Doug T.


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.

like image 39
Timo Geusch Avatar answered Jan 03 '23 19:01

Timo Geusch