Note that there are some explanatory texts on larger screens.

plurals
  1. PONeed help understanding using C++ map as an associative array
    primarykey
    data
    text
    <p>I was going through Josuttis's "Using Map's as associative arrays" (from <a href="http://www.cppstdlib.com/" rel="nofollow noreferrer">The C++ Standard Library - A Tutorial and Reference, 2nd Edition</a>) and came across <a href="https://stackoverflow.com/questions/1540182/using-a-stdmap-as-an-associative-array">Using a std::map as an associative array</a> on Stack Overflow. Now I have more questions on the constructors that are called when inserting into a map.</p> <p>Here is my sample program (not using best coding practices; please excuse me for that):</p> <pre><code>class C { public: string s; C() { cout &lt;&lt; "default " &lt;&lt; endl;} C(const string&amp; p) : s(p) { cout &lt;&lt; "one param" &lt;&lt; endl;} C(const C&amp; obj) { if (this != &amp;obj) { s = obj.s; } cout &lt;&lt; "copy constr" &lt;&lt; endl; } C&amp; operator = (const C&amp; obj) { if (this != &amp;obj) { s = obj.s; } cout &lt;&lt; "copy initializer" &lt;&lt; endl; return *this; } }; int main() { map&lt;int,C&gt; map1; C obj("test"); cout &lt;&lt; "Inserting using index" &lt;&lt; endl; map1[1] = obj; cout &lt;&lt; "Inserting using insert / pair" &lt;&lt; endl; map1.insert(make_pair(2,obj)); } </code></pre> <p>The output for this program is:</p> <pre><code>one param Inserting using index default copy constr copy constr copy initializer Inserting using insert / pair copy constr copy constr copy constr copy constr </code></pre> <p>I was assuming that initializing the map by index should call the default constructor and followed by the assignment operator. </p> <p>But executing <code>map1[1] = obj</code> creates following output;</p> <pre><code>Inserting using index default copy constr copy constr copy initializer </code></pre> <p>Can someone help me to understand the initialization better?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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