|
-
April 13th, 2010, 07:32 AM
#5
Re: Prefferred method of inserting in map
 Originally Posted by sunnypalsingh
std::map associate key with only one value. So, why would others not replace?
'insert()' will actually fail if the given key already exists within the map.
 Originally Posted by sunnypalsingh
I am not sure but I think others will also be first constructed then they will be put in map. So, why inefficient?
The inefficiency happens whenever the key is not yet in the map. If it is in the map, '[]' simply returns a reference to the associated value and assigns the new value. However, in the case it is not, it cannot return a reference. Thus, it will create an object using the default constructor and return a reference to the object accordingly. The value then gets assigned.
'insert()' saves the first step....and constructs the object with the given value in one step thus saving the cost of creating a temporary object.
Last edited by Andreas Masur; April 13th, 2010 at 04:43 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|