Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The performance depends on the underlying container used. As already mentioned, <code>stack</code> is an adapter, the underlying container can be <code>deque</code> (the default), or <code>vector</code>, or <code>list</code> (all in <code>std</code> namespace). </p> <p>Following is an example of performance comparison. As the type to be stored is not clearly mentioned in the question, I am assuming it to be unsigned int. Feel free to change it per your requirements. The example constructs a stack of 100K items.</p> <p>Contents of <code>stack.cpp</code></p> <pre><code>#include &lt;stack&gt; #include &lt;vector&gt; #include &lt;list&gt; #include &lt;deque&gt; #include &lt;assert.h&gt; typedef unsigned int Type; #ifdef USE_VECTOR typedef std::stack&lt; Type, std::vector&lt; Type &gt; &gt; StackType; #elif USE_LIST typedef std::stack&lt; Type, std::list&lt; Type &gt; &gt; StackType; #else typedef std::stack&lt; Type, std::deque&lt; Type &gt; &gt; StackType; #endif int main() { StackType mystack; for( unsigned int i = 0; i &lt; 100 * 1024; ++i ) { mystack.push( i ); } assert( mystack.size() == 100 * 1024 ); return 0; } </code></pre> <p>Execution comparison:</p> <pre><code>$ g++ -DUSE_VECTOR stack.cpp -o stack; time ./stack real 0m0.023s user 0m0.030s sys 0m0.031s $ g++ -DUSE_LIST stack.cpp -o stack; time ./stack real 0m0.144s user 0m0.186s sys 0m0.030s $ g++ stack.cpp -o stack; time ./stack real 0m0.024s user 0m0.030s sys 0m0.015s asaha@nedata8 ~/code $ </code></pre> <p>The above numbers are result of single run. <strong>To achieve statistically significant numbers run each variation large number of times, and observe the mean and standard deviation.</strong></p> <p>Apparently, <code>deque</code> and <code>vector</code> results in similar performance, whereas <code>list</code> is worse.</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