Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The boost::assign library has all sorts of neat stuff to help out initializing the contents of a container. My thought that this could be used to avoid explicitly iterating through the map. Unfortunately, maps are curious beasts difficult to initialize because the keys must be unique. The bottom line is that a simple for loop is probably the best way to initialize a map. It may not be super elegant, but it gets the job done and is immediatly comprehensible by anyone with any acquaintance with the STL.</p> <pre><code>map &lt;int,string&gt; myMap; for( int k=0;k&lt;1000;k++) myMap.insert(pair&lt;int,string&gt;(k,string(""))); </code></pre> <p>The rest of this post describes the journey I took to reach the above conclusion.</p> <p>The boost::assign makes it simple to assign a small number of values to a map.</p> <pre><code>map&lt;string,int&gt; m; insert( m )( "Bar", 1 )( "Foo", 2 ); </code></pre> <p>or</p> <pre><code> map&lt;int,int&gt; next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6); </code></pre> <p>In your case, where you want to initialize the entire map with the same value, there are the utilities repeat and repeat_fun.<br> Something like this should work with a multimap ( untested code snippet )</p> <pre><code>pair&lt;int,string&gt; init( 0,string("")); multimap &lt;int,string&gt; myMap = repeat(1000,init); </code></pre> <p>As Konrad Rudolph as pointed out, you cannot initialize a map with the same exact value, because the keys must be unique.</p> <p>This makes life much more complex ( fun? ). Something like this, perhaps:</p> <pre><code>map &lt;int,string&gt; myMap; struct nextkey { int start; nextkey( s ) : start( s ) {} pair&lt;int,string&gt; operator () () { return pair&lt;int,string&gt;(start++,string("")); } }; myMap = repeat_fun(1000,nextkey(0)); </code></pre> <p>Now, this is getting so complex, I now think a simple iteration IS the way to go</p> <pre><code>map &lt;int,string&gt; myMap; for( int k=0;k&lt;1000;k++) myMap.insert(pair&lt;int,string&gt;(k,string(""))); </code></pre>
 

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