Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Err...</p> <p>try the method:</p> <pre><code>std::vector&lt;T&gt;::reserve(x) </code></pre> <p>It will enable you to reserve enough memory for x items without initializing any (your vector is still empty). Thus, there won't be reallocation until to go over x.</p> <p>The second point is that vector won't initialize the values to zero. Are you testing your code in debug ?</p> <p>After verification on g++, the following code:</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; struct MyStruct { int m_iValue00 ; int m_iValue01 ; } ; int main() { MyStruct aaa, bbb, ccc ; std::vector&lt;MyStruct&gt; aMyStruct ; aMyStruct.push_back(aaa) ; aMyStruct.push_back(bbb) ; aMyStruct.push_back(ccc) ; aMyStruct.resize(6) ; // [EDIT] double the size for(std::vector&lt;MyStruct&gt;::size_type i = 0, iMax = aMyStruct.size(); i &lt; iMax; ++i) { std::cout &lt;&lt; "[" &lt;&lt; i &lt;&lt; "] : " &lt;&lt; aMyStruct[i].m_iValue00 &lt;&lt; ", " &lt;&lt; aMyStruct[0].m_iValue01 &lt;&lt; "\n" ; } return 0 ; } </code></pre> <p>gives the following results:</p> <pre><code>[0] : 134515780, -16121856 [1] : 134554052, -16121856 [2] : 134544501, -16121856 [3] : 0, -16121856 [4] : 0, -16121856 [5] : 0, -16121856 </code></pre> <p>The initialization you saw was probably an artifact.</p> <p>[EDIT] After the comment on resize, I modified the code to add the resize line. The resize effectively calls the default constructor of the object inside the vector, but if the default constructor does nothing, then nothing is initialized... I still believe it was an artifact (I managed the first time to have the whole vector zerooed with the following code:</p> <pre><code>aMyStruct.push_back(MyStruct()) ; aMyStruct.push_back(MyStruct()) ; aMyStruct.push_back(MyStruct()) ; </code></pre> <p>So... :-/</p> <p>[EDIT 2] Like already offered by Arkadiy, the solution is to use an inline constructor taking the desired parameters. Something like</p> <pre><code>struct MyStruct { MyStruct(int p_d1, int p_d2) : d1(p_d1), d2(p_d2) {} int d1, d2 ; } ; </code></pre> <p>This will probably get inlined in your code.</p> <p>But you should anyway study your code with a profiler to be sure this piece of code is the bottleneck of your application.</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