Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problem with insert is that <code>make_pair</code> will create a pair of the wrong type so the passed object will need a conversion to a proper pair type to be passed to <code>insert</code>.</p> <p>Actually in a former version the C++ standard mandated <code>map::operator[]</code> to behave as <code>insert</code> (thus forcing an inefficient implementation). Later the text was relaxed allowing a better implementation.</p> <p>Note anyway that for standard containers the elements are considered to be "values", i.e. the implementation is free to copy things around and you get no guarantees about how many copies will be made.</p> <p>You can see the <code>make_pair</code> problem by changing the code to</p> <pre><code> mymap2.insert(std::pair&lt;const Key, int&gt;(k, 1)); </code></pre> <h2>Longer explanation</h2> <p>The problem is that <code>make_pair</code> will create an <code>std::pair&lt;Key, int&gt;</code> value but <code>insert</code> signature wants instead a <code>const std::pair&lt;const Key, int&gt;&amp;</code> (note that <code>std::map::value_type</code> is a pair with a <code>const</code> first element).</p> <p>These two types are incompatible and unrelated so to be able to make the call another pair must be created copying both key and value and this is where an extra key duplication occurs.</p> <p>Even if it could be apparently "logical" that a <code>pair&lt;X, Y&gt;</code> should be directly usable where <code>pair&lt;const X, Y&gt;</code> is expected this is not true in C++ and it's one of the logical problems of the const-correctness concept (it doesn't scale by composition).</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload