Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to avoid reallocation using the STL (C++)
    primarykey
    data
    text
    <p>This question is derived from the topic:</p> <p><a href="https://stackoverflow.com/questions/2280655/vector-reserve-c">vector reserve c++</a></p> <p>I am using a datastructure of the type <code>vector&lt;vector&lt;vector&lt;double&gt; &gt; &gt;</code>. It is not possible to know the size of each of these vector (except the outer one) before items (<code>double</code>s) are added. I can get an approximate size (upper bound) on the number of items in each "dimension".</p> <p>A solution with the shared pointers might be the way to go, but I would like to try a solution where the <code>vector&lt;vector&lt;vector&lt;double&gt; &gt; &gt;</code> simply has <code>.reserve()</code>ed enough space (or in some other way has allocated enough memory).</p> <p>Will <code>A.reserve(500)</code> (assumming 500 is the size or, alternatively an upper bound on the size) be enough to hold "2D" vectors of large size, say [1000][10000]?</p> <p>The reason for my question is mainly because I cannot see any way of reasonably estimating the size of the interior of <code>A</code> at the time of <code>.reserve(500)</code>.</p> <p>An example of my question:</p> <pre><code>vector&lt;vector&lt;vector&lt;int&gt; &gt; &gt; A; A.reserve(500+1); vector&lt;vector&lt;int&gt; &gt; temp2; vector&lt;int&gt; temp1 (666,666); for(int i=0;i&lt;500;i++) { A.push_back(temp2); for(int j=0; j&lt; 10000;j++) { A.back().push_back(temp1); } } </code></pre> <p>Will this ensure that no reallocation is done for A?</p> <p>If <code>temp2.reserve(100000)</code> and <code>temp1.reserve(1000)</code> were added at creation will this ensure no reallocation at all will occur at all?</p> <p>In the above please disregard the fact that memory could be wasted due to conservative <code>.reserve()</code> calls.</p> <p>Thank you all in advance!</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