如何在使用 make_unique<T[]>() 制作的模板类型数组上使用 std::fill?

May*_*kar 0 c++ c++14

我想为我的二维矩阵创建类。我使用了以下代码

#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;
    }
  }
};
Run Code Online (Sandbox Code Playgroud)

现在我想用 替换循环,std::fill但不知何故我无法做到这一点。所有示例都在std::vector<T>或 上std::array<T>。任何人都可以帮我解决这个问题吗?

编辑 1: @StoryTeller - Unslander Monica 提到的一种方式是

std::fill(&data[0], &data[0] + row*col , def);
Run Code Online (Sandbox Code Playgroud)

有没有更干净的方法?

Sto*_*ica 5

std::fill需要一对定义有效范围的迭代器(可以是指针)。在你的情况下,范围是从第一个元素的地址&data[0],到一个过去的结束&data[0] + row*col。将其转换为调用,我们得到

std::fill(&data[0], &data[0] + row*col , def);
Run Code Online (Sandbox Code Playgroud)

或等价物,但在我看来并不那么明显:

std::fill(data.get(), data.get() + row*col , def);
Run Code Online (Sandbox Code Playgroud)

另一种方法是让标准库自己做算术,并使用互补算法std::fill_n。从而产生这些选项之一。

std::fill_n(&data[0], row*col , def);
std::fill_n(data.get(), row*col , def);
Run Code Online (Sandbox Code Playgroud)

  • @MayukhSarkar 您需要使用“data.get()”来获取实际的指针。 (3认同)