CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 7 of 7

Threaded View

  1. #5
    Join Date
    May 2000
    Location
    KY, USA
    Posts
    18,652

    Re: Prefferred method of inserting in map

    Quote Originally Posted by sunnypalsingh View Post
    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.

    Quote Originally Posted by sunnypalsingh View Post
    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
  •  





Click Here to Expand Forum to Full Width

Featured