Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>When you want a square or 2d grid, do something similar to what the compiler does for multidimensional arrays (real ones, not an array of pointers to arrays) and store a single large array which you index correctly.</p> <p>Example using the Matrix class below:</p> <pre><code>struct Map { private: Matrix&lt;MapCell&gt; cells; public: void loadMap() { Matrix&lt;MapCell&gt; cells (WIDTH, HEIGHT); for (int i = 0; i &lt; WIDTH; i++) { for (int j = 0; j &lt; HEIGHT; j++) { // modify cells[i][j] } } swap(this-&gt;cells, cells); // if there's any problem loading, don't modify this-&gt;cells // Matrix swap guarantees no-throw (because vector swap does) // which is a common and important aspect of swaps } }; </code></pre> <p>Variants of matrix classes abound, and there are many ways to tailor for specific use. Here's an example in less than 100 lines that gets you 80% or more of what you need:</p> <pre><code>#include &lt;algorithm&gt; #include &lt;memory&gt; #include &lt;vector&gt; template&lt;class T, class A=std::allocator&lt;T&gt; &gt; struct Matrix { typedef T value_type; typedef std::vector&lt;value_type, A&gt; Container; Matrix() : _b(0) {} Matrix(int a, int b, value_type const&amp; initial=value_type()) : _b(0) { resize(a, b, initial); } Matrix(Matrix const&amp; other) : _data(other._data), _b(other._b) {} Matrix&amp; operator=(Matrix copy) { swap(*this, copy); return *this; } bool empty() const { return _data.empty(); } void clear() { _data.clear(); _b = 0; } int dim_a() const { return _b ? _data.size() / _b : 0; } int dim_b() const { return _b; } value_type* operator[](int a) { return &amp;_data[a * _b]; } value_type const* operator[](int a) const { return &amp;_data[a * _b]; } void resize(int a, int b, value_type const&amp; initial=value_type()) { if (a == 0) { b = 0; } _data.resize(a * b, initial); _b = b; } friend void swap(Matrix&amp; a, Matrix&amp; b) { using std::swap; swap(a._data, b._data); swap(a._b, b._b); } template&lt;class Stream&gt; friend Stream&amp; operator&lt;&lt;(Stream&amp; s, Matrix const&amp; value) { s &lt;&lt; "&lt;Matrix at " &lt;&lt; &amp;value &lt;&lt; " dimensions " &lt;&lt; value.dim_a() &lt;&lt; 'x' &lt;&lt; value.dim_b(); if (!value.empty()) { bool first = true; typedef typename Container::const_iterator Iter; Iter i = value._data.begin(), end = value._data.end(); while (i != end) { s &lt;&lt; (first ? " [[" : "], ["); first = false; s &lt;&lt; *i; ++i; for (int b = value._b - 1; b; --b) { s &lt;&lt; ", " &lt;&lt; *i; ++i; } } s &lt;&lt; "]]"; } s &lt;&lt; '&gt;'; return s; } private: Container _data; int _b; }; </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