Skip to Main Content
C++ Cookbook
book

C++ Cookbook

by D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell
November 2005
Beginner to intermediate content levelBeginner to intermediate
594 pages
16h 23m
English
O'Reilly Media, Inc.
Content preview from C++ Cookbook

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; ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ System Programming Cookbook

C++ System Programming Cookbook

Onorato Vaticone

Publisher Resources

ISBN: 0596007612Supplemental ContentErrata Page