11.14. Implementing a Dynamically Sized Matrix

Problem

You need to store and represent Matricies of numbers where the dimensions (number of rows and columns) are not known at compile time.

Solution

Example 11-28 provides a general purpose and efficient implementation of a dynamically sized matrix class using the stride iterator from Recipe 11.12 and a valarray.

Example 11-28. matrix.hpp

#ifndef MATRIX_HPP
#define MATRIX_HPP

#include "stride_iter.hpp" // see Recipe 11.12 #include <valarray> #include <numeric> #include <algorithm> template<class Value_T> class matrix { public: // public typedefs typedef Value_T value_type; typedef matrix self; typedef value_type* iterator; typedef const value_type* const_iterator; typedef Value_T* row_type; typedef stride_iter<value_type*> col_type; typedef const value_type* const_row_type; typedef stride_iter<const value_type*> const_col_type; // constructors matrix() : nrows(0), ncols(0), m() { } matrix(int r, int c) : nrows(r), ncols(c), m(r * c) { } matrix(const self& x) : m(x.m), nrows(x.nrows), ncols(x.ncols) { } template<typename T> explicit matrix(const valarray<T>& x) : m(x.size() + 1), nrows(x.size()), ncols(1) { for (int i=0; i<x.size(); ++i) m[i] = x[i]; } // allow construction from matricies of other types template<typename T> explicit matrix(const matrix<T>& x) : m(x.size() + 1), nrows(x.nrows), ncols(x.ncols) { copy(x.begin(), x.end(), m.begin()); } // public functions int rows() const { return nrows; } int cols() const { return ncols; ...

Get C++ Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.