Appendix E. Source Code for the file scpp_matrix.hpp

#ifndef __SCPP_MATRIX_HPP_INCLUDED__ #define __SCPP_MATRIX_HPP_INCLUDED__ #include <ostream> #include <vector> #include "scpp_assert.hpp" namespace scpp { // Two-dimensional rectangular matrix. template <typename T> class matrix { public: typedef unsigned size_type; matrix(size_type num_rows, size_type num_cols) : rows_(num_rows), cols_(num_cols), data_(num_rows * num_cols) { SCPP_TEST_ASSERT(num_rows > 0, "Number of rows in a matrix must be positive"); SCPP_TEST_ASSERT(num_cols > 0, "Number of columns in a matrix must be positive"); } matrix(size_type num_rows, size_type num_cols, const T& init_value) : rows_(num_rows), cols_(num_cols), data_(num_rows * num_cols, init_value) { SCPP_TEST_ASSERT(num_rows > 0, "Number of rows in a matrix must be positive"); SCPP_TEST_ASSERT(num_cols > 0, "Number of columns in a matrix must be positive"); } size_type num_rows() const { return rows_; } size_type num_cols() const { return cols_; } // Accessors: return element by row and column. T& operator() ( size_type row, size_type col ) { return data_[ index( row, col ) ]; } const T& operator() ( size_type row, size_type col ) const { return data_[ index( row, col ) ]; } private: size_type rows_, cols_; std::vector<T> data_; size_type index(size_type row, size_type col) const { SCPP_TEST_ASSERT(row < rows_, "Row " << row << " must be less than " << rows_); SCPP_TEST_ASSERT(col < cols_, "Column " << col << " must be less than " << cols_); return ...

Get Safe C++ 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.