Note that there are some explanatory texts on larger screens.

plurals
  1. PORemove elements (and change size) of std::vector without affecting allocated memory
    primarykey
    data
    text
    <p>I'm using code such as the following:</p> <pre><code>const int MY_SIZE = 100000; std::vector&lt;double&gt; v; v.reserve(MY_SIZE); // add no more than MY_SIZE elements to the vector f(v); v.clear(); // again, add no more than MY_SIZE elements to the vector f(v); v.clear(); // // etc... // </code></pre> <p>The point of my code is to store <code>MY_SIZE</code> <code>double</code>'s and then perform an operation <code>f(std::vector&lt;double&gt;)</code> on those elements. After I fill up the vector and perform the operation, I want to get rid of all the elements (and reset <code>std::vector::size()</code> to 0), and then add more elements. But, the key here is that I do <strong>not</strong> want to cause the space in memory allocated for the vector to be changed.</p> <p>Note than I'm never going to add more than <code>MY_SIZE</code> elements to <code>v</code>, so <code>v</code> should never need to reallocate more memory than was allocated by <code>v.reserve(MY_SIZE)</code>.</p> <p>So, when I call <code>v.clear()</code> in the above code, will it affect in any way the amount of space allocated by <code>v.reserve(MY_SIZE)</code> or the location in memory of <code>v.begin()</code>?</p> <hr> <p><strong>Related question</strong>: If I call <code>v.erase(v.begin(),v.begin()+v.size())</code>, will it affect in any way the amount of space allocated by <code>v.reserve(MY_SIZE)</code> or the location in memory of <code>v.begin()</code>?</p> <p>If I really just wanted to erase all the elements, I would call <code>clear()</code>. But I'm wondering about this related question because there are occasions when I need to erase only the first X elements of <code>v</code>, and on these occasions I want to keep the memory allocated by <code>v.reserve(MY_SIZE)</code> and I don't want the location of <code>v</code> to change.</p>
    singulars
    1. This table or related slice is empty.
    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.
    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