Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>vector being faster to build or clear than deque or list is to be expected; it's a simpler data structure.</p> <p>With regard to <a href="http://en.cppreference.com/w/cpp/container/vector/push_back" rel="nofollow noreferrer"><code>vector::push_back</code></a>, it has to do two things: </p> <ol> <li>check the vector is big enough to hold the new item.</li> <li>insert the new item.</li> </ol> <p>You can generally speed things up by eliminating step 1 by simply resizing the vector and using <a href="http://en.cppreference.com/w/cpp/container/vector/operator_at" rel="nofollow noreferrer"><code>operator[]</code></a> to set items.</p> <p><strong>UPDATE:</strong> Original poster asked for an example. The code below times 128 mega insertions, and outputs</p> <pre><code>push_back : 2.04s reserve &amp; push_back : 1.73s resize &amp; place : 0.48s </code></pre> <p>when compiled and run with g++ -O3 on Debian/Lenny on an old P4 machine.</p> <pre><code>#include &lt;iostream&gt; #include &lt;time.h&gt; #include &lt;vector&gt; int main(int,char**) { const size_t n=(128&lt;&lt;20); const clock_t t0=clock(); { std::vector&lt;unsigned char&gt; a; for (size_t i=0;i&lt;n;i++) a.push_back(i); } const clock_t t1=clock(); { std::vector&lt;unsigned char&gt; a; a.reserve(n); for (size_t i=0;i&lt;n;i++) a.push_back(i); } const clock_t t2=clock(); { std::vector&lt;unsigned char&gt; a; a.resize(n); for (size_t i=0;i&lt;n;i++) a[i]=i; } const clock_t t3=clock(); std::cout &lt;&lt; "push_back : " &lt;&lt; (t1-t0)/static_cast&lt;float&gt;(CLOCKS_PER_SEC) &lt;&lt; "s" &lt;&lt; std::endl; std::cout &lt;&lt; "reserve &amp; push_back : " &lt;&lt; (t2-t1)/static_cast&lt;float&gt;(CLOCKS_PER_SEC) &lt;&lt; "s" &lt;&lt; std::endl; std::cout &lt;&lt; "resize &amp; place : " &lt;&lt; (t3-t2)/static_cast&lt;float&gt;(CLOCKS_PER_SEC) &lt;&lt; "s" &lt;&lt; std::endl; return 0; } </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