Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'd recommend you use a library such as <a href="http://eigen.tuxfamily.org/index.php?title=Main_Page" rel="nofollow">Eigen</a> (very fast) or the <a href="http://www.boost.org/doc/libs/1_49_0/libs/numeric/ublas/doc/index.htm" rel="nofollow">boost uBLAS matrix</a> (not so fast, relatively speaking) class. Still, if you're trying to learn the way to do this, there's no harm in building your own class. The standard way of doing this is with templates for the type. You can also, with a little bit of further investigation use templates for the size (left as an exercise to the reader).</p> <pre><code>template &lt;typename T&gt; class matrix { private: T *_m; std::size_t _rows; std::size_t _cols; public: matrix(std::size_t rows, std::size_t cols) : _m(new T[rows*cols]), _rows(rows), _cols(cols) {} matrix(matrix&lt;T&gt;&amp;&amp; src) : _m(src._m), _rows(src._rows), _cols(src._cols) { src._m = NULL; src._rows = 0; src._cols = 0; } matrix&lt;T&gt;&amp; operator=(matrix&lt;T&gt;&amp;&amp; src) { delete[] this-&gt;_m; this-&gt;_m = src._m; this-&gt;_rows = src._rows; this-&gt;_cols = src._cols; src._m = NULL; src._rows = 0; src._cols = 0; return *this; } virtual ~matrix() { delete[] this-&gt;_m; } inline float&amp; operator()(std::size_t r, std::size_t c) { assert(r &lt; this-&gt;_rows &amp;&amp; c &lt; this-&gt;_cols); return this-&gt;_m[r*this-&gt;_cols + c]; } inline std::size_t rows() { return this-&gt;_rows; } inline std::size_t cols() { return this-&gt;_cols; } }; template &lt;typename T&gt; matrix&lt;T&gt; operator*(const matrix&lt;T&gt;&amp; l, const matrix&lt;T&gt;&amp; r) { assert(l.cols() == r.rows()); matrix&lt;T&gt; rv(l.rows(), r.cols()); for (std::size_t r = 0; r &lt; rv.rows(); ++r) for (std::size_t c = 0; c &lt; rv.cols(); ++c); { rv(r, c) = (T) 0; for (std::size_t i = 0; i &lt; l.cols(); ++i) rv(r, c) += l(r, i) * r(i, c); } return rv; } </code></pre> <p>This has a few C++11 aspects to it, namely the move constructor and assignment operator. If you are not using C++11 yet, replace them with traditional copy and assignment operators respectively. Also, this is a kind of naive multiplier. There are some efficiencies you can employ to eliminate many of the matrix element lookups by replacing them with an iterator style construct instead.</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