I have implemented a Matrix class that allocates memory using unique_ptr
. How to make it more diverse and optimized in terms of memory usage and efficiency?
//
// Created by Mayukh Sarkar on 26/12/19.
//
#ifndef DP2_MATRIX_H
#define DP2_MATRIX_H
#include <cstdio>
#include <memory>
#include <algorithm>
template <typename T>
class Matrix {
private:
size_t row{};
size_t col{};
std::unique_ptr<T[]> data;
public:
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);
std::fill_n(data.get(), row*col, def);
}
// Overload the [] operator for the 2d array like access
T* operator[](int r) {
if (r >= row) {
throw std::out_of_range("Can not access out of bound element!");
}
return &this->data[r*col];
}
// 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;
}
// Set all the values of the Matrix
void setValues(T value) {
std::fill_n(data.get(), row*col, value);
}
// 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
I want to specifically optimize the []operator
overloading because I feel it is not good to handle pointers directly. Any suggestions?