0

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?

Mayukh Sarkar
  • 2,289
  • 1
  • 14
  • 38

1 Answers1

5

std::fill expects a pair of iterators (that could be pointers) which define a valid range. In your case the range is from the address of the first element &data[0], up to one past the end &data[0] + row*col. Translating it into an invocation, we get

std::fill(&data[0], &data[0] + row*col , def);

or the equivalent, but in my opinion not quite as obvious:

std::fill(data.get(), data.get() + row*col , def);

Another approach, is to let the standard library do the arithmetic itself, and use the complementary algorithm std::fill_n. Thus producing one of these options.

std::fill_n(&data[0], row*col , def);
std::fill_n(data.get(), row*col , def);
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458