I want to create class for my 2d matrix. I have used the following code
#include <memory>
#include <algorithm>
template <typename T>
class Matrix {
private:
int row{};
int col{};
std::unique_ptr<T[]> data; // We are going to store data into a 1d array
public:
explicit Matrix(int row, int col, T def) {
// Creates a T type matrix of row rows and col columns
// and initialize each element by def
this->row = row;
this->col = col;
this->data = std::make_unique<T[]>(row*col);
for(int i=0; i<row*col; i++) {
data[i] = def;
}
}
void setValues(T value) {
// Set the value in all the elements
for (int i=0; i<row*col; i++) {
data[i] = value;
}
}
};
Now I want to replace the loops with std::fill
but somehow I am not able to do this. All the examples are on std::vector<T>
or on std::array<T>
. Can anyone help me with this please?
EDIT 1: One way as @StoryTeller - Unslander Monica mentioned is
std::fill(&data[0], &data[0] + row*col , def);
Is there any cleaner way?