Note that there are some explanatory texts on larger screens.

plurals
  1. POWhich one is more optimized for accessing array?
    primarykey
    data
    text
    <p>Solving the following exercise:</p> <blockquote> <p>Write three different versions of a program to print the elements of ia. One version should use a range for to manage the iteration, the other two should use an ordinary for loop in one case using subscripts and in the other using pointers. In all three programs write all the types directly. That is, do not use a type alias, auto, or decltype to simplify the code.[C++ Primer]</p> </blockquote> <p>a question came up: <strong>Which of these methods for accessing array is optimized in terms of speed and why?</strong> </p> <hr> <p><strong>My Solutions:</strong></p> <ol> <li><p>Foreach Loop:</p> <pre><code>int ia[3][4]={{1,2,3,4},{5,6,7,8},{9,10,11,12}}; for (int (&amp;i)[4]:ia) //1st method using for each loop for(int j:i) cout&lt;&lt;j&lt;&lt;" "; </code></pre></li> <li><p>Nested for loops:</p> <pre><code>for (int i=0;i&lt;3;i++) //2nd method normal for loop for(int j=0;j&lt;4;j++) cout&lt;&lt;ia[i][j]&lt;&lt;" "; </code></pre></li> <li><p>Using pointers:</p> <pre><code>int (*i)[4]=ia; for(int t=0;t&lt;3;i++,t++){ //3rd method. using pointers. for(int x=0;x&lt;4;x++) cout&lt;&lt;(*i)[x]&lt;&lt;" "; </code></pre></li> <li><p>Using <code>auto</code>:</p> <pre><code>for(auto &amp;i:ia) //4th one using auto but I think it is similar to 1st. for(auto j:i) cout&lt;&lt;j&lt;&lt;" "; </code></pre></li> </ol> <hr> <p><strong>Benchmark result using <code>clock()</code></strong></p> <pre class="lang-none prettyprint-override"><code>1st: 3.6 (6,4,4,3,2,3) 2nd: 3.3 (6,3,4,2,3,2) 3rd: 3.1 (4,2,4,2,3,4) 4th: 3.6 (4,2,4,5,3,4) </code></pre> <p>Simulating each method 1000 times: </p> <pre class="lang-none prettyprint-override"><code>1st: 2.29375 2nd: 2.17592 3rd: 2.14383 4th: 2.33333 Process returned 0 (0x0) execution time : 13.568 s </code></pre> <p>Compiler used:MingW 3.2 c++11 flag enabled. IDE:CodeBlocks</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.
    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