Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>There are a number of things that are potential issues in your code, but the most obvious thing that may be causing the <code>printMap</code> not to work as expected is this while loop.</p> <pre><code>map&lt;string, int&gt;::iterator it = myMap.begin(); cout&lt;&lt;"test"&lt;&lt;endl; while(it!=myMap.end()){ cout&lt;&lt;(*it).first&lt;&lt;" ==&gt; "&lt;&lt;(*it).second&lt;&lt;endl; } </code></pre> <p>Nowhere do you increment the iterator so either nothing will be printed (if the map is empty) or else the first item will printed over and over again and the loop won't terminate.</p> <p>The idiomatic way to write this loop would be as a for loop.</p> <pre><code>for (std::map&lt;string, int&gt;::iterator it = myMap.begin(); it != myMap.end(); ++it) { std::cout &lt;&lt; it-&gt;first &lt;&lt; " ==&gt; " &lt;&lt; it-&gt;second &lt;&lt; '\n'; } </code></pre> <p>The other issue is that your <code>addToMap</code> function probably isn't working as intended because you pass the map to the function <em>by value</em> and this means that the map that the function is adding an item to is actually a copy of the map that was passed in.</p> <p>When control is passed to the calling function this copy is destroyed and the map that was passed it is still empty.</p> <p>To pass a map by reference you need to add <code>&amp;</code> to the type of the parameter in the function declaration.</p> <p>i.e. in the headfile, the the <code>MapWorks</code> class definition:</p> <pre><code>void addToMap(string myword, map&lt;string, int&gt;&amp; myMap); </code></pre> <p>and in the source file:</p> <pre><code>void MapWorks::addToMap(string myword, map&lt;string, int&gt;&amp; myMap) { // definition... } </code></pre> <hr> <p>Your use of references for dynamically allocated objects is unusual, to say the least. For your purposes, I don't see any point to doing:</p> <pre><code>ReadWords &amp;rnw = *new ReadNumWords(); </code></pre> <p>when you delete the object at the end of the same function in which it is created. You can just do this (exactly as you do with <code>MapWorks mw;</code>).</p> <pre><code>ReadNumWords rnw; </code></pre> <p>If you have to use dynamically allocated objects, just using pointers rather than references is much more usual but it is highly recommended to use some sort of a smart pointer so that you don't have to remember to call <code>delete</code> explicitly.</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