title: Recommended way to insert elements into map
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/326062/in-stl-maps-is-it-better-to-use-mapinsert-than">In STL maps, is it better to use map::insert than []?</a>  </p>
  </blockquote>
  
  
  
  <p>I was wondering, when I insert element into map, what is the recommended way. Should I</p>
  
  <pre><code>map[key] = value;
  </code></pre>
  
  <p>or</p>
  
  <pre><code>map.insert(std::pair&lt;key_type, value_type&gt;(key, value));
  </code></pre>
  
  <p>I did the following quick test:</p>
  
  <pre><code>#include &lt;map&gt;
  #include &lt;string&gt;
  #include &lt;iostream&gt;
  
  class Food {
  public:
      Food(const std::string&amp; name) : name(name) { std::cout &lt;&lt; "constructor with string parameter" &lt;&lt; std::endl; }
      Food(const Food&amp; f) : name(f.name) { std::cout &lt;&lt; "copy" &lt;&lt; std::endl; }
      Food&amp; operator=(const Food&amp; f) { name = f.name; std::cout &lt;&lt; "=" &lt;&lt; std::endl; return *this; } 
      Food() { std::cout &lt;&lt; "default" &lt;&lt; std::endl; }
      std::string name;
  };
  
  int main() {
      std::map&lt;std::string, Food&gt; m0;
  
  /*
  1) constructor with string parameter
  2) copy
  3) copy
  4) copy
  */
      m0.insert(std::pair&lt;std::string, Food&gt;("Key", Food("Ice Cream")));
  
  /*
  1) constructor with string parameter
  2) default
  3) copy
  4) copy
  5) =
  */
      // If we do not provide default constructor.
      // C2512: 'Food::Food' : no appropriate default constructor available
      m0["Key"] = Food("Ice Cream");
  }
  </code></pre>
  
  <ol>
  <li>I realize by using member function <code>insert</code>, less value's function call will be involved. So, is using <code>insert</code> a recommended way?</li>
  <li>Why default constructor is needed, when <code>map[key] = value</code> way is being used?</li>
  </ol>
  
  <p>I know that <code>insert</code> doesn't overwrite existence key value pair, but <code>map[key] = value</code> does. However, is this the only factor I take into consideration, when try to choose among the both?</p>
  
  <p>How about</p>
  
  <ol>
  <li><strong>Performance</strong></li>
  <li><strong>Availability of value's default constructor</strong></li>
  <li><strong>???</strong></li>
  </ol>