Created
December 26, 2019 19:18
-
-
Save MayukhSobo/9333704fe73ee8e4f4f92162635ba991 to your computer and use it in GitHub Desktop.
A basic Matrix class
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef DP2__MATRIX_H | |
#define DP2__MATRIX_H | |
#include <algorithm> | |
#include <cstdio> | |
#include <memory> | |
#include <stdexcept> | |
template <typename T> | |
class Matrix { | |
private: | |
size_t row{}; | |
size_t col{}; | |
std::unique_ptr<T[]> data; | |
void boundscheck(int r, int c) const { | |
if (!(0 <= r && r < row && 0 <= c && c < col)) { | |
throw std::out_of_range("Can not access out of bound element!"); | |
} | |
} | |
public: | |
// Set all the values of the Matrix | |
void setValues(T value) { | |
std::fill_n(data.get(), row*col, value); | |
} | |
explicit Matrix(size_t row, size_t col, T def) { | |
// Create a matrix of row X col and initialize | |
// each element of the matrix with def | |
this->row = row; | |
this->col = col; | |
this->data = std::make_unique<T[]>(this->row * this->col); | |
setValues(def); | |
} | |
// Overload the [] operator for the 2d array like access | |
T* operator[](int r) { | |
return &this->data[r * col]; | |
} | |
const T* operator[](int r) const { | |
return &this->data[r * col]; | |
} | |
T& at(int r, int c) { | |
boundscheck(r, c); | |
return this->data[r * col + c]; | |
} | |
const T& at(int r, int c) const { | |
boundscheck(r, c); | |
return this->data[r * col + c]; | |
} | |
// Overload the << operator for console logging | |
friend std::ostream& operator<< (std::ostream& os, Matrix &mObj) { | |
auto shape = mObj.shape(); | |
for(int i=0; i< shape.first; i++) { | |
for(int j=0; j<shape.second; j++) { | |
os << mObj[i][j] << " "; | |
} | |
os << "\n"; | |
} | |
return os; | |
} | |
// Get row and col values | |
std::pair<size_t, size_t> shape() const { | |
return std::make_pair(this->row, this->col); | |
} | |
}; | |
#endif //DP2__MATRIX_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment