Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The usual way of implementing a 2 dimensional array in C++ would be to wrap it in a class, using <code>std::vector&lt;int&gt;</code>, and have class accessors which calculate the index. However: </p> <p>Any questions concerning optimization can only be answered by measuring, and even then, they are only valid for the compiler you are using, on the machine on which you do the measurements.</p> <p>If you write:</p> <pre><code>int array[2][3] = { ... }; </code></pre> <p>and then something like:</p> <pre><code>for ( int i = 0; i != 2; ++ i ) { for ( int j = 0; j != 3; ++ j ) { // do something with array[i][j]... } } </code></pre> <p>It's hard to imagine a compiler which doesn't actually generate something along the lines of:</p> <pre><code>for ( int* p = array, p != array + whatever; ++ p ) { // do something with *p } </code></pre> <p>This is one of the most fundamental optimizations around, and has been for at least 30 years.</p> <p>If you dynamically allocate as you propose, the compiler will <em>not</em> be able to apply this optimization. And even for a single access: the matrix has poorer locality, and requires more memory accesses, so would likely be less performant.</p> <p>If you're in C++, you would normally write a <code>Matrix</code> class, using <code>std::vector&lt;int&gt;</code> for the memory, and calculating the indexes explicitly using multiplication. (The improved locality will probably result in better performance, despite the multiplication.) This could make it more difficult for the compiler to do the above optimization, but if this turns out to be an issue, you can always provide specialized iterators for handling this one particular case. You end up with more readable and more flexible code (e.g. the dimensions don't have to be constant), at little or no loss of performance.</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